ScheduledThreadPoolExecutor提供的两个方法来完成延迟及定时执行任务
scheduleAtFixedRate及scheduleWithFixedDelay
大致执行步骤:
1)创建task任务
2)将任务加入到延迟队列
3)启用线程通过getTask方法从队列中获取任务
4)延迟队列中的take方法获取任务时,会根据等待时间阻塞任务;
针对scheduleAtFixedRate源码分析:
public ScheduledFuture<?> scheduleAtFixedRate(
// 要执行的任务
Runnable command,
// 第一次延迟执行时间
long initialDelay,
// 两次执行相隔时间
long period,
// 时间单位
TimeUnit unit) {
if (command == null || unit == null)
throw new NullPointerException();
if (period <= 0L)