scheduledThreadPoolExecutor是咋实现周期任务调度的( 二 )

/** * Specialized variant of ThreadPoolExecutor.execute for delayed tasks. */private void delayedExecute(Runnable command) { if (isShutdown()) { reject(command); return; } // Prestart a thread if necessary. We cannot prestart it // running the task because the task (probably) shouldn\u0026#39;t be // run yet, so thread will just idle until delay elapses. if (getPoolSize() \u0026lt; getCorePoolSize()) prestartCoreThread(); super.getQueue().add(command);}上面写的最后一个方法是将任务加入线程池的方法。//检查池子是否关闭public boolean isShutdown() { return runState != RUNNING;}如果池子关闭,调用程序中的拒绝处理Handler拒绝执行该任务并返回/** * Invokes the rejected execution handler for the given command. * 该方法存在于父类ThreadPoolExecutor当中-*/void reject(Runnable command) { handler.rejectedExecution(command, this);}------------------------------------------------------------------------------------------------------------由于ScheduledThreadPoolExecutor没有maximumPoolSize,只有corePoolSize,所以构造方法public ScheduledThreadPoolExecutor(int corePoolSize) { super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS, new DelayedWorkQueue());}public ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory) { super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS, new DelayedWorkQueue(), threadFactory);}public ScheduledThreadPoolExecutor(int corePoolSize, RejectedExecutionHandler handler) { super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS, new DelayedWorkQueue(), handler);}所以不会有创建小于corePoolSize线程数----\u0026gt;任务加入BlockingQueue-----\u0026gt;队列满创建临时线程的--------的步骤,而是直接加入BlockingQueue队列,一般是无界的BlockingQueue----------------------------------------------------------------------------------------------------------------------------------------与ThreadPoolExecutor的主要区别在于使用了DelayedWorkQueue作为存放任务的队列DelayedWorkQueue中封装的是DelayQueue private final DelayQueue\u0026lt;RunnableScheduledFuture\u0026gt; dq = new DelayQueue\u0026lt;RunnableScheduledFuture\u0026gt;();DelayQueue是一个优先队列,是一个heap其实


推荐阅读