带你学会区分Scheduled Thread Pool Executor 与Timer
摘要:本文简单介绍下Scheduled Thread Pool Executor类与Timer类的区别,Scheduled Thread Pool Executor类相比于Timer类来说,究竟有哪些优势,以及二者分别实现任务调度的简单示例。
本文分享自华为云社区《【高并发】ScheduledThreadPoolExecutor与Timer的区别和简单示例》,作者:冰 河 。
JDK 1.5开始提供Scheduled Thread Pool Executor类,Scheduled Thread Pool Executor类继承Thread Pool Executor类重用线程池实现了任务的周期性调度功能。在JDK 1.5之前,实现任务的周期性调度主要使用的是Timer类和Timer Task类。本文,就简单介绍下Scheduled Thread Pool Executor类与Timer类的区别,Scheduled Thread Pool Executor类相比于Timer类来说,究竟有哪些优势,以及二者分别实现任务调度的简单示例。
二者的区别
线程角度
- Timer是单线程模式,如果某个TimerTask任务的执行时间比较久,会影响到其他任务的调度执行。
- Scheduled Thread Pool Executor是多线程模式,并且重用线程池,某个Scheduled Future Task任务执行的时间比较久,不会影响到其他任务的调度执行。
系统时间敏感度
- Timer调度是基于操作系统的绝对时间的,对操作系统的时间敏感,一旦操作系统的时间改变,则Timer的调度不再精确。
- Scheduled Thread Pool Executor调度是基于相对时间的,不受操作系统时间改变的影响。
是否捕获异常
- Timer不会捕获Timer Task抛出的异常,加上Timer又是单线程的。一旦某个调度任务出现异常,则整个线程就会终止,其他需要调度的任务也不再执行。
- Scheduled Thread Pool Executor基于线程池来实现调度功能,某个任务抛出异常后,其他任务仍能正常执行。
任务是否具备优先级
- Timer中执行的Timer Task任务整体上没有优先级的概念,只是按照系统的绝对时间来执行任务。
- Scheduled Thread Pool Executor中执行的Scheduled Future Task类实现了java.lang.Comparable 接口和java.util.concurrent.Delayed 接口,这也就说明了Scheduled Future Task类中实现了两个非常重要的方法,一个是java.lang.Comparable 接口的compare To方法,一个是java.util.concurrent.Delayed接口的get Delay方法。在Scheduled Future Task类中compare To方法实现了任务的比较,距离下次执行的时间间隔短的任务会排在前面,也就是说,距离下次执行的时间间隔短的任务的优先级比较高。而get Delay 方法则能够返回距离下次任务执行的时间间隔。
是否支持对任务排序
- Timer不支持对任务的排序。
- Scheduled Thread Pool Executor类中定义了一个静态内部类Delayed Work Queue ,Delayed Work Queue 类本质上是一个有序队列,为需要调度的每个任务按照距离下次执行时间间隔的大小来排序
能否获取返回的结果
- Timer中执行的Timer Task类只是实现了java.lang.Runnable 接口,无法从Timer Task 中获取返回的结果。
- Scheduled Thread Pool Executor中执行的Scheduled Future Task类继承了Future Task 类,能够通过Future来获取返回的结果。
通过以上对Scheduled Thread Pool Executor 类和Timer类的分析对比,相信在JDK 1.5之后,就没有使用Timer来实现定时任务调度的必要了。
二者简单的示例
这里,给出使用Timer和Scheduled Thread Pool Executor 实现定时调度的简单示例,为了简便,我这里就直接使用匿名内部类的形式来提交任务。
Timer类简单示例
源代码示例如下所示。
package io.binghe.concurrent.lab09;
import java.util.Timer;
import java.util.TimerTask;
/**
* @author binghe
* @version 1.0.0
* @description 测试Timer
*/
public class TimerTest {
public static void main(String[] args) throws InterruptedException {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
System.out.println("测试Timer类");
}
}, 1000, 1000);
Thread.sleep(10000);
timer.cancel();
}
}
运行结果如下所示。
测试Timer类
测试Timer类
测试Timer类
测试Timer类
测试Timer类
测试Timer类
测试Timer类
测试Timer类
测试Timer类
测试Timer类
Scheduled Thread Pool Executor类简单示例
源代码示例如下所示。
package io.binghe.concurrent.lab09;
import java.util.concurrent.*;
/**
* @author binghe
* @version 1.0.0
* @description 测试ScheduledThreadPoolExecutor
*/
public class ScheduledThreadPoolExecutorTest {
public static void main(String[] args) throws InterruptedException {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("测试测试ScheduledThreadPoolExecutor");
}
}, 1, 1, TimeUnit.SECONDS);
//主线程休眠10秒
Thread.sleep(10000);
System.out.println("正在关闭线程池...");
// 关闭线程池
scheduledExecutorService.shutdown();
boolean isClosed;
// 等待线程池终止
do {
isClosed = scheduledExecutorService.awaitTermination(1, TimeUnit.DAYS);
System.out.println("正在等待线程池中的任务执行完成");
} while(!isClosed);
System.out.println("所有线程执行结束,线程池关闭");
}
}
运行结果如下所示。
测试测试ScheduledThreadPoolExecutor
测试测试ScheduledThreadPoolExecutor
测试测试ScheduledThreadPoolExecutor
测试测试ScheduledThreadPoolExecutor
测试测试ScheduledThreadPoolExecutor
测试测试ScheduledThreadPoolExecutor
测试测试ScheduledThreadPoolExecutor
测试测试ScheduledThreadPoolExecutor
测试测试ScheduledThreadPoolExecutor
正在关闭线程池...
测试测试ScheduledThreadPoolExecutor
正在等待线程池中的任务执行完成
所有线程执行结束,线程池关闭
注意:关于Timer和Scheduled Thread Pool Executor 还有其他的使用方法,这里,我就简单列出以上两个使用示例,更多的使用方法大家可以自行实现。
带你学会区分Scheduled Thread Pool Executor 与Timer的更多相关文章
- 实例分析Scheduled Thread Pool Executor与Timer的区别
摘要:JDK 1.5开始提供Scheduled Thread PoolExecutor类,Scheduled Thread Pool Executor类继承Thread Pool Executor类重 ...
- 通过Thread Pool Executor类解析线程池执行任务的核心流程
摘要:ThreadPoolExecutor是Java线程池中最核心的类之一,它能够保证线程池按照正常的业务逻辑执行任务,并通过原子方式更新线程池每个阶段的状态. 本文分享自华为云社区<[高并发] ...
- 8000字详解Thread Pool Executor
摘要:Java是如何实现和管理线程池的? 本文分享自华为云社区<JUC线程池: ThreadPoolExecutor详解>,作者:龙哥手记 . 带着大厂的面试问题去理解 提示 请带着这些问 ...
- ThreadPoolExecutor – Java Thread Pool Example(如何使用Executor框架创建一个线程池)
Java thread pool manages the pool of worker threads, it contains a queue that keeps tasks waiting to ...
- ThreadPoolExecutor – Java Thread Pool Example
https://www.journaldev.com/1069/threadpoolexecutor-java-thread-pool-example-executorservice Java t ...
- ThreadPoolExecutor – Java Thread Pool Example(java线程池创建和使用)
Java thread pool manages the pool of worker threads, it contains a queue that keeps tasks waiting to ...
- DUBBO Thread pool is EXHAUSTED!
一.问题 在测试环境遇到的异常信息,如下: 16-10-17 00:00:00.033 [New I/O server worker #1-6] WARN com.alibaba.dubbo.com ...
- [Done][DUBBO] dubbo Thread pool is EXHAUSTED!
异常信息: com.alibaba.dubbo.remoting.ExecutionException: class com.alibaba.dubbo.remoting.transport.disp ...
- The threads in the thread pool will process the requests on the connections concurrently.
https://docs.oracle.com/javase/tutorial/essential/concurrency/pools.html Most of the executor implem ...
- Anti Pattern - ThreadLocal variables with Thread Pool(转)
In a previous post, I wrote the usage and benefits of ThreadLocal based instance variables in concur ...
随机推荐
- docker 仓库-Harbor
docker 仓库之分布式 Harbor: Harbor 是一个用于存储和分发docker镜像的企业级Registry服务器,由于Vmware 开源,其通过添加一些企业必须的功能特性,例如安全.标识和 ...
- Vue源码学习(十三):实现watch(一):方法,对象
好家伙, 代码出了点bug,暂时只能实现这两种形式 完整代码已开源https://github.com/Fattiger4399/analytic-vue.git Vue:watch的多种使用方法 ...
- 彻底搞懂CAP理论(电商系统)
1.理解CAP CAP是 Consistency.Availability.Partition tolerance三个词语的缩写,分别表示一致性.可用性.分区容忍性. 下边我们分别来解释: 为了方便对 ...
- Util应用框架基础(六) - 日志记录(一) - 正文
本文介绍Util应用框架如何记录日志. 日志记录共分4篇,本文是正文,后续还有3篇分别介绍写入不同日志接收器的安装和配置方法. 概述 日志记录对于了解系统执行情况非常重要. Asp.Net Core ...
- python计算代码运行时间
记录一下自己用python编写计算运行时间的代码 时间类 import time import numpy as np # 编写时间类来方便操作 class Timer: def __init__(s ...
- 【luogu题解】P9749 [CSP-J 2023] 公路
\(Meaning\) \(Solution\) 这道题我来讲一个不一样的解法:\(dp\) 在写 \(dp\) 之前,我们需要明确以下几个东西:状态的表示,状态转移方程,边界条件和答案的表示. 状态 ...
- [ABC244G] Construct Good Path
Problem Statement You are given a simple connected undirected graph with $N$ vertices and $M$ edges. ...
- Microsoft Edge 分屏 推荐
前言: 很早之前就在 Edge Dev 频道的更新公告中看到过 Edge 的新分屏功能,当时没怎么注意,昨天看文档的时候发现 Edge 的侧边栏可以拖动当作一个"虚假的"分屏页面来 ...
- 阿里云AnalyticDB基于Flink CDC+Hudi实现多表全增量入湖实践
湖仓一体(LakeHouse)是大数据领域的重要发展方向,提供了流批一体和湖仓结合的新场景.阿里云AnalyticDB for MySQL基于 Apache Hudi 构建了新一代的湖仓平台,提供日志 ...
- 安装华企盾DSC防泄密软件造成CAD2012卡住怎么办?
将下图目录的.exe程序删除或者重命名