// 初始化周期线程池
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
// 关键方法,周期执行任务
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
long initialDelay,
long period,
TimeUnit unit) {
if (command == null || unit == null)
throw new NullPointerException();
if (period <= 0)
throw new IllegalArgumentException();
// FutureTask子类
ScheduledFutureTask<Void> sft =
new ScheduledFutureTask<Void>(command,
null,
triggerTime(initialDelay, unit),
unit.toNanos(period));
// 默认不装饰,返回sft
RunnableScheduledFuture<Void> t = decorateTask(command, sft);
sft.outerTask = t;
delayedExecute(t);
return t;
}
// 将ScheduledFutureTask(间接Runnable实现类)放入延迟队列
// 等待工作线程将ScheduledFutureTask从延迟队列中拉出来执行其run()方法
private void delayedExecute(RunnableScheduledFuture<?> task) {
if (isShutdown())
reject(task);
else {
// 放入初始化的DelayedWorkQueue延迟队列
super.getQueue().add(task);
if (isShutdown() &&
!canRunInCurrentRunState(task.isPeriodic()) &&
remove(task))
task.cancel(false);
else
ensurePrestart();
}
}
// 保证有工作线程运行
// 1、工作线程数小于核心线程数,添加一个没有任务的工作线程
// 2、工作线程数为0,添加一条非核心线程
void ensurePrestart() {
int wc = workerCountOf(ctl.get());
if (wc < corePoolSize)
addWorker(null, true);
else if (wc == 0)
addWorker(null, false);
}
ScheduledFutureTask
public void run() {
// scheduleAtFixedRate的构造函数传入的执行周期,不为0,返回true
boolean periodic = isPeriodic();
// 线程池是否是running或者shutdown状态
if (!canRunInCurrentRunState(periodic))
cancel(false);
else if (!periodic)
ScheduledFutureTask.super.run();
// 正常应该执行这个方法,拉取延迟队列的任务执行后,
// 再将任务重新放入延迟队列
else if (ScheduledFutureTask.super.runAndReset()) {
setNextRunTime();
reExecutePeriodic(outerTask);
}
}
DelayedWorkQueue
延迟队列中放的都是RunnableScheduledFuture实现类,而上面的ScheduledFutureTask就是其中一种,当从延迟队列拉出一条RunnableScheduledFuture后,得到其设置的过期时间,然后wait到过期时间,然后再返回这个RunnableScheduledFuture任务,让线程池工作线程去执行。
FutureTask
FutureTask的get方法是阻塞的,再初始化FutureTask的时候,状态变量state为NEW,在调用get方法时,如果状态是未完成的,那么就LockSupport.park阻塞。直到run方法执行完后,将状态设置为NORMAL,唤醒所有调用get阻塞的线程