网站首页 > 技术文章 正文
ScheduledThreadPoolExecutor是JDK5提供的可执行定时任务的一个工具类,可以在多线程环境下延迟执行任务或者定期执行任务;和Timer类似,它也提供了三种定时模式:
- 延迟执行任务
- 固定延迟的定期执行(fixed delay)
- 按照固定的周期执行(fixed rate)
延迟执行任务
任务将按照给定的时间延迟delay后开始执行;对应的方法如下:
schedule(Runnable command, long delay, TimeUnit unit)
schedule(Callable<V> callable, long delay, TimeUnit unit)
下面我们通过一个例子检验下结果是否正确:
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
PrintUtil.print("start schedule a task.");
executor.schedule(new Runnable() {
@Override
public void run() {
PrintUtil.print("task is running.");
}
}, 5, TimeUnit.SECONDS);
我们计划了一个5秒钟后执行的任务,通过打印结果可以看到确实按照给定时间执行了:
15:44:07--start schedule a task.
15:44:12--task is running.
固定延迟的定期执行
任务第一次按照给定的初始延迟initialDelay执行,后续每一次执行的时间为上一次任务的结束时间加上给定的period后执行;对应的方法如下:
scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
同样我们通过一个例子检验下结果是否正确:
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
PrintUtil.print("start schedule a task.");
executor.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
PrintUtil.print("task is running.");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, 0, 5, TimeUnit.SECONDS);
我们计划了一个定期(每5秒钟)延迟执行的任务,第一次任务立即执行,每次任务执行时长2秒钟,通过打印的日志我们可以看到每次任务开始执行的时间为:上次任务结束时间+5秒钟:
15:55:16--start schedule a task.
15:55:16--task is running.
15:55:18--task is finished.
15:55:23--task is running.
15:55:25--task is finished.
15:55:30--task is running.
15:55:32--task is finished.
按照固定的周期执行
任务第一次按照给定的初始延迟initialDelay执行,后续每一次执行的时间为固定的时间间隔period,如果线程池中工作线程不够则任务顺延执行;对应的方法如下:
scheduleWithFixedDelay(Runnable command, long initialDelay, long period, TimeUnit unit)
同样我们通过一个例子检验下结果是否正确:
ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);
PrintUtil.print("start schedule a task.");
executor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
PrintUtil.print("task is running.");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
PrintUtil.print("task is finished.");
}
}, 0, 5, TimeUnit.SECONDS);
我们创建了一个核心线程池为10的ScheduledThreadPoolExecutor,并计划了一个定期(每5秒钟)执行一次的任务,过打印的日志我们可以看到每次任务开始执行的时间为:上次任务开始时间+5秒钟:
16:02:43--start schedule a task.
16:02:43--task is running.
16:02:45--task is finished.
16:02:48--task is running.
16:02:50--task is finished.
上面的例子都是计划了一个任务,如果是有多个定时任务同时执行会怎么样呢?
如果线程足够并且CPU资源足够,那就会同时执行,如果线程或者CPU资源不够那只能排队执行了。有兴趣的话可以克隆文末的测试代码,里面提供了一些测试的例子。
底层原理
ScheduledThreadPoolExecutor是如何保证我们计划的任务都是按照正确的时间点执行的呢?
其内部实现了一个阻塞队列DelayedWorkQueue,所有的任务都会放到这个队列里。这个阻塞队列内部通过一个数组来保存这些任务,并且基于最小堆排序,按照每个任务的下次执行时间进行排序,这样就保证了执行线程拿到的这个队列中的第一个元素就是最接近当前时间执行的任务了。
相关的源码如下:
// 保存定时任务的队列
private RunnableScheduledFuture<?>[] queue = new RunnableScheduledFuture<?>[INITIAL_CAPACITY];
// 最小堆排序相关的方法
private void siftUp(int k, RunnableScheduledFuture<?> key)
private void siftDown(int k, RunnableScheduledFuture<?> key)
那时间上是如何保证的呢?
DelayedWorkQueue重写了take和poll方法,利用了AQS的ConditionObject机制使当前线程休眠,等时间到了再唤醒线程去拿第一个任务。
关于AQS和ConditonObject的介绍,可以参考下文末的链接。
public RunnableScheduledFuture<?> take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
for (;;) {
RunnableScheduledFuture<?> first = queue[0];
if (first == null)
available.await();
else {
long delay = first.getDelay(NANOSECONDS);
if (delay <= 0)
return finishPoll(first);
first = null; // don't retain ref while waiting
if (leader != null)
available.await();
else {
Thread thisThread = Thread.currentThread();
leader = thisThread;
try {
available.awaitNanos(delay);
} finally {
if (leader == thisThread)
leader = null;
}
}
}
}
} finally {
if (leader == null && queue[0] != null)
available.signal();
lock.unlock();
}
}
优点
作为对JDK1.3推出的Timer的替代,ScheduledThreadPoolExecutor有如下优点:
- 它支持多个定时任务同时执行,而Timer是单线程执行的
- 它通过System.nanoTime()保证了任务执行时间不受操作系统时间变化的影响
- 一个定时任务抛出异常,其他定时任务不受影响,而Timer却不支持这一点
Demo代码
参考文章
猜你喜欢
- 2024-11-21 Java 线程池 | ThreadPoolExecutor 原理分析
- 2024-11-21 面试侃集合 | DelayQueue篇
- 2024-11-21 springboot-如何配置线程池实现定时任务
- 2024-11-21 ThreadPoolExecutor源码解析
- 2024-11-21 心跳与超时:高并发高性能的时间轮超时器
- 2024-11-21 Java线程池ThreadPoolExecutor 线程池
- 2024-11-21 8 个线程池的深渊巨坑,使用不当直接生产事故!!!
- 2024-11-21 java线程池核心类ThreadPoolExecutor的应用
- 2024-11-21 Java线程池:ExecutorService 开发入门
- 2024-11-21 面试官:你给我说一下什么是时间轮吧?
你 发表评论:
欢迎- 最近发表
- 标签列表
-
- oraclesql优化 (66)
- 类的加载机制 (75)
- feignclient (62)
- 一致性hash算法 (71)
- dockfile (66)
- 锁机制 (57)
- javaresponse (60)
- 查看hive版本 (59)
- phpworkerman (57)
- spark算子 (58)
- vue双向绑定的原理 (68)
- springbootget请求 (58)
- docker网络三种模式 (67)
- spring控制反转 (71)
- data:image/jpeg (69)
- base64 (69)
- java分页 (64)
- kibanadocker (60)
- qabstracttablemodel (62)
- java生成pdf文件 (69)
- deletelater (62)
- com.aspose.words (58)
- android.mk (62)
- qopengl (73)
- epoch_millis (61)
本文暂时没有评论,来添加一个吧(●'◡'●)