定时任务线程池
ScheduledThreadPoolExecutor,可以执行定时任务的线程池。这里学习它的基本原理。
定时任务线程池,和普通线程池不同的地方在于,它使用一个延迟队列,延迟队列使用最小堆作为它的数据结构,它会按照任务的执行顺序,把最先执行的任务放到第一个,线程会获取第一个任务的延迟时长,然后阻塞指定时长,阻塞完成后,去执行任务。对于周期性执行的任务,执行完成后,会计算下一次启动时间,然后把任务重新提交到延迟队列。
源码分析
定时任务线程池的继承体系
定时任务线程池继承了ThreadPoolExecutor,同时实现了ScheduledExecutorService,这个接口定义了定时调度相关的功能
public class ScheduledThreadPoolExecutor
extends ThreadPoolExecutor
implements ScheduledExecutorService {
ScheduledExecutorService:定义了定时调度的功能
public interface ScheduledExecutorService extends ExecutorService {
// 定时调度1次的任务
public ScheduledFuture<?> schedule(Runnable command,
long delay, TimeUnit unit);
// 定时调度1次的任务,有返回值
public <V> ScheduledFuture<V> schedule(Callable<V> callable,
long delay, TimeUnit unit);
// 以固定频率调度的任务
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
long initialDelay,
long period,
TimeUnit unit);
// 以固定延迟调度的任务
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
long initialDelay,
long delay,
TimeUnit unit);
}
描述定时任务的类
描述定时任务的类:ScheduledThreadPoolExecutor的内部类ScheduledFutureTask
// ScheduledFutureTask:是定时任务线程池的内部类,封装了任务的启动时间、周期时间(隔多长时间执行一次),
// 任务在延迟队列中的索引、任务序号
private class ScheduledFutureTask<V>
extends FutureTask<V> implements RunnableScheduledFuture<V> {
// 任务的启动时间,单位是纳秒
private long time;
// 任务的执行周期,单位是纳秒
private final long period;
// 任务在队列中的索引
int heapIndex;
// 任务序号,通过原子类生成
private final long sequenceNumber;
// 持有自己的实例
RunnableScheduledFuture<V> outerTask = this;
// 构造方法,参数1 异步任务,参数2 结果,参数3 任务的启动时间,参数4 任务的周期时间
ScheduledFutureTask(Runnable r, V result, long ns, long period) {
super(r, result);
this.time = ns;
this.period = period;
this.sequenceNumber = sequencer.getAndIncrement
6478


定时任务线程池源码&spm=1001.2101.3001.11974&articleId=146054466&d=1&t=3&u=1b6218daf8be40aa86cbdeb8c14a3b55)

被折叠的 条评论
为什么被折叠?



