Java并发包中 ScheduledThreadPoolExecutor 原理探究
介绍
上篇文章中有提到过 Executors ,这是一个工具类,他提供了很多静态方法返回不同的线程池实例。 而其中的 newScheduledThreadPool 方法就提供了成成延迟线程池的实例。其中线程池队列是DelayWorkQueue 其和 DelayQueue 一样是一个延迟队列。
类图结构

ScheduledFutureTask 是具有返回值的任务,继承自FutureTask。FutureTask 的内部有一个变量 state 用来表示任务的状态。
1 | private volatile int state; |
有可能的任务状态转换途径为:
NEW -> COMPLETING -> NORMAL
NEW -> COMPLETING -> EXCEPTIONAL
NEW -> CANCLLED
NEW -> INTERRUPTING -> INTERRUPTED
ScheduledFutureTask 内部还有一个变量 period 用来表示任务的类型。当 period 为0的时候说明当前任务是一次性的,period为负数的时候说明当前任务为 fixed-delay 固定延迟的定时可重复执行任务,period为整数说明当前任务为 fixed-rate 任务,是固定频率的定时可重复执行任务。
1 | public static ScheduledExecutorService newScheduledThreadPool(intcorePoolSize) { |
原理剖析
主要讲解三个重要函数
- schedule(Callable< V > callable, long delay, TimeUnit unit)
- scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)
- scheduleAtFixedRate(Callable< V > callable, long delay, TimeUnit unit)
schedule(Callable< V > callable, long delay, TimeUnit unit)
该方法的作用是 提交一个延迟执行的任务 ,任务从提交时间算起延迟单位为 unit 的delay 时间后开始执行。 提交的任务不是周期性任务, 任务只会执行一次。
1 | public ScheduledFuture<?> schedule(Runnable command, |
我们来看一下 ScheduledFutureTask 是如何执行任务的
1 | public void run() { |
总结
ScheduledThreadPoolExecutor 的实现原理是通过内部使用 DelayQueue 延迟队列存放具体任务,以达到延迟的效果。