摘要:本文简单介绍下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的更多相关文章

  1. 实例分析Scheduled Thread Pool Executor与Timer的区别

    摘要:JDK 1.5开始提供Scheduled Thread PoolExecutor类,Scheduled Thread Pool Executor类继承Thread Pool Executor类重 ...

  2. 通过Thread Pool Executor类解析线程池执行任务的核心流程

    摘要:ThreadPoolExecutor是Java线程池中最核心的类之一,它能够保证线程池按照正常的业务逻辑执行任务,并通过原子方式更新线程池每个阶段的状态. 本文分享自华为云社区<[高并发] ...

  3. 8000字详解Thread Pool Executor

    摘要:Java是如何实现和管理线程池的? 本文分享自华为云社区<JUC线程池: ThreadPoolExecutor详解>,作者:龙哥手记 . 带着大厂的面试问题去理解 提示 请带着这些问 ...

  4. ThreadPoolExecutor – Java Thread Pool Example(如何使用Executor框架创建一个线程池)

    Java thread pool manages the pool of worker threads, it contains a queue that keeps tasks waiting to ...

  5. ThreadPoolExecutor – Java Thread Pool Example

    https://www.journaldev.com/1069/threadpoolexecutor-java-thread-pool-example-executorservice   Java t ...

  6. ThreadPoolExecutor – Java Thread Pool Example(java线程池创建和使用)

    Java thread pool manages the pool of worker threads, it contains a queue that keeps tasks waiting to ...

  7. DUBBO Thread pool is EXHAUSTED!

    一.问题 在测试环境遇到的异常信息,如下: 16-10-17 00:00:00.033 [New I/O server worker #1-6] WARN  com.alibaba.dubbo.com ...

  8. [Done][DUBBO] dubbo Thread pool is EXHAUSTED!

    异常信息: com.alibaba.dubbo.remoting.ExecutionException: class com.alibaba.dubbo.remoting.transport.disp ...

  9. 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 ...

  10. Anti Pattern - ThreadLocal variables with Thread Pool(转)

    In a previous post, I wrote the usage and benefits of ThreadLocal based instance variables in concur ...

随机推荐

  1. JavaBean 之Hello World(入门实例)

    本文主要参考<JavaEE企业应用实战>的例子,经过调试成功. 前言:如果多个jsp页面需要重复使用某段代码,我们可以把这段代码定义成Java类的方法,让后让多个jsp页面调用该方法即可, ...

  2. Spring5学习随笔-Spring5的第一个程序(环境搭建、日志框架整合)

    第二章.第一个Spring程序 1.软件版本 1.JDK1.8+ 2.Maven3.5+ 3.IDEA2018+ 4.SpringFramework 5.1.4 官网:www.spring.io 2. ...

  3. 使用 Hexo 搭建个人博客并部署到云服务器

    目录 1 整体流程 2. 本地环境准备 2.1 安装 Node.js 和 Git 2.2 安装 Hexo 3. 服务端环境准备 3.1 Nginx 环境配置 3.1.1 安装 Nginx 3.1.2 ...

  4. Miniconda安装及搭建

    Miniconda安装配置 下载Miniconda Miniconda下载地址 最新版 Miniconda For Windows 下载链接 Windows 安装配置 修改Powershell执行策略 ...

  5. echarts官网文档打开慢的解决方法

    echarts官网文档打开慢的解决方法由于我们在做大数据屏的时候需要很多echarts图表,这个过程中也会遇到需要查询echarts官网文档.手册.配置项的时候,但是由于网站在国外,访问很慢或者打不开 ...

  6. [python] 基于Tablib库处理表格数据

    Tablib是一个用于处理电子表格(如 Excel,CSV,JSON)的Python 库.它提供了一种简单而强大的方式来操作和处理数据.利用Tablib,我们可以轻松地读取.写入.过滤和转换各种类型的 ...

  7. Codeforces Round 909 (Div3)(本菜鸟只补到了E)

    Codeforces Round 909 (Div.3) A. Game with Integers 水题,就是可以被3整除的输出"Second",不能被3整除的输出"F ...

  8. 使用halo快速搭建应用文档中心

    背景 之前我写了一篇,用gitbook搭建文档中心,gitbook是一款搭建博客的技术,是静态博客技术,不带后台管理系统.不带数据库,要发文章的话,是通过提供markdown文件,渲染成html,通过 ...

  9. .NET 程序员-开源项目【藏】

    Json.NET http://json.codeplex.com/ Json.Net是一个读写Json效率比较高的.Net框架.Json.Net 使得在.Net环境下使用Json更加简单.通过Lin ...

  10. netty整合websocket(完美教程)

    websocket的介绍: WebSocket是一种在网络通信中的协议,它是独立于HTTP协议的.该协议基于TCP/IP协议,可以提供双向通讯并保有状态.这意味着客户端和服务器可以进行实时响应,并且这 ...