Java 多线程之Timer与ScheduledExecutorService
1、Timer管理延时任务的缺陷
a、以前在项目中也经常使用定时器,比如每隔一段时间清理项目中的一些垃圾文件,每个一段时间进行数据清洗;然而Timer是存在一些缺陷的,因为Timer在执行定时任务时只会创建一个线程,所以如果存在多个任务,且任务时间过长,超过了两个任务的间隔时间,会发生一些缺陷:下面看例子:
Timer的源码:
- public class Timer {
- /**
- * The timer task queue. This data structure is shared with the timer
- * thread. The timer produces tasks, via its various schedule calls,
- * and the timer thread consumes, executing timer tasks as appropriate,
- * and removing them from the queue when they're obsolete.
- */
- private TaskQueue queue = new TaskQueue();
- /**
- * The timer thread.
- */
- private TimerThread thread = new TimerThread(queue);
TimerThread是Thread的子类,可以看出内部只有一个线程。下面看个例子:
- package com.zhy.concurrency.timer;
- import java.util.Timer;
- import java.util.TimerTask;
- public class TimerTest
- {
- private static long start;
- public static void main(String[] args) throws Exception
- {
- TimerTask task1 = new TimerTask()
- {
- @Override
- public void run()
- {
- System.out.println("task1 invoked ! "
- + (System.currentTimeMillis() - start));
- try
- {
- Thread.sleep(3000);
- } catch (InterruptedException e)
- {
- e.printStackTrace();
- }
- }
- };
- TimerTask task2 = new TimerTask()
- {
- @Override
- public void run()
- {
- System.out.println("task2 invoked ! "
- + (System.currentTimeMillis() - start));
- }
- };
- Timer timer = new Timer();
- start = System.currentTimeMillis();
- timer.schedule(task1, 1000);
- timer.schedule(task2, 3000);
- }
- }
定义了两个任务,预计是第一个任务1s后执行,第二个任务3s后执行,但是看运行结果:
- task1 invoked ! 1000
- task2 invoked ! 4000
task2实际上是4后才执行,正因为Timer内部是一个线程,而任务1所需的时间超过了两个任务间的间隔导致。下面使用ScheduledThreadPool解决这个问题:
- package com.zhy.concurrency.timer;
- import java.util.TimerTask;
- import java.util.concurrent.Executors;
- import java.util.concurrent.ScheduledExecutorService;
- import java.util.concurrent.TimeUnit;
- public class ScheduledThreadPoolExecutorTest
- {
- private static long start;
- public static void main(String[] args)
- {
- /**
- * 使用工厂方法初始化一个ScheduledThreadPool
- */
- ScheduledExecutorService newScheduledThreadPool = Executors
- .newScheduledThreadPool(2);
- TimerTask task1 = new TimerTask()
- {
- @Override
- public void run()
- {
- try
- {
- System.out.println("task1 invoked ! "
- + (System.currentTimeMillis() - start));
- Thread.sleep(3000);
- } catch (Exception e)
- {
- e.printStackTrace();
- }
- }
- };
- TimerTask task2 = new TimerTask()
- {
- @Override
- public void run()
- {
- System.out.println("task2 invoked ! "
- + (System.currentTimeMillis() - start));
- }
- };
- start = System.currentTimeMillis();
- newScheduledThreadPool.schedule(task1, 1000, TimeUnit.MILLISECONDS);
- newScheduledThreadPool.schedule(task2, 3000, TimeUnit.MILLISECONDS);
- }
- }
输出结果:
- task1 invoked ! 1001
- task2 invoked ! 3001
符合我们的预期结果。因为ScheduledThreadPool内部是个线程池,所以可以支持多个任务并发执行。
2、Timer当任务抛出异常时的缺陷
如果TimerTask抛出RuntimeException,Timer会停止所有任务的运行:
- package com.zhy.concurrency.timer;
- import java.util.Date;
- import java.util.Timer;
- import java.util.TimerTask;
- public class ScheduledThreadPoolDemo01
- {
- public static void main(String[] args) throws InterruptedException
- {
- final TimerTask task1 = new TimerTask()
- {
- @Override
- public void run()
- {
- throw new RuntimeException();
- }
- };
- final TimerTask task2 = new TimerTask()
- {
- @Override
- public void run()
- {
- System.out.println("task2 invoked!");
- }
- };
- Timer timer = new Timer();
- timer.schedule(task1, 100);
- timer.scheduleAtFixedRate(task2, new Date(), 1000);
- }
- }
上面有两个任务,任务1抛出一个运行时的异常,任务2周期性的执行某个操作,输出结果:
task2 invoked!
- Exception in thread "Timer-0" java.lang.RuntimeException
- at com.zhy.concurrency.timer.ScheduledThreadPoolDemo01$1.run(ScheduledThreadPoolDemo01.java:24)
- at java.util.TimerThread.mainLoop(Timer.java:512)
- at java.util.TimerThread.run(Timer.java:462)
由于任务1的一次,任务2也停止运行了。。。下面使用ScheduledExecutorService解决这个问题:
- package com.zhy.concurrency.timer;
- import java.util.Date;
- import java.util.Timer;
- import java.util.TimerTask;
- import java.util.concurrent.Executors;
- import java.util.concurrent.ScheduledExecutorService;
- import java.util.concurrent.TimeUnit;
- public class ScheduledThreadPoolDemo01
- {
- public static void main(String[] args) throws InterruptedException
- {
- final TimerTask task1 = new TimerTask()
- {
- @Override
- public void run()
- {
- throw new RuntimeException();
- }
- };
- final TimerTask task2 = new TimerTask()
- {
- @Override
- public void run()
- {
- System.out.println("task2 invoked!");
- }
- };
- ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
- pool.schedule(task1, 100, TimeUnit.MILLISECONDS);
- pool.scheduleAtFixedRate(task2, 0 , 1000, TimeUnit.MILLISECONDS);
- }
- }
代码基本一致,但是ScheduledExecutorService可以保证,task1出现异常时,不影响task2的运行:
- task2 invoked!
- task2 invoked!
- task2 invoked!
- task2 invoked!
- task2 invoked!<span style="font-family: Arial, Helvetica, sans-serif;">...</span>
3、Timer执行周期任务时依赖系统时间
Timer执行周期任务时依赖系统时间,如果当前系统时间发生变化会出现一些执行上的变化,ScheduledExecutorService基于时间的延迟,不会由于系统时间的改变发生执行变化。
上述,基本说明了在以后的开发中尽可能使用ScheduledExecutorService(JDK1.5以后)替代Timer。
Java 多线程之Timer与ScheduledExecutorService的更多相关文章
- Java多线程之ConcurrentSkipListMap深入分析(转)
Java多线程之ConcurrentSkipListMap深入分析 一.前言 concurrentHashMap与ConcurrentSkipListMap性能测试 在4线程1.6万数据的条件下, ...
- JAVA多线程之wait/notify
本文主要学习JAVA多线程中的 wait()方法 与 notify()/notifyAll()方法的用法. ①wait() 与 notify/notifyAll 方法必须在同步代码块中使用 ②wait ...
- JAVA多线程之volatile 与 synchronized 的比较
一,volatile关键字的可见性 要想理解volatile关键字,得先了解下JAVA的内存模型,Java内存模型的抽象示意图如下: 从图中可以看出: ①每个线程都有一个自己的本地内存空间--线程栈空 ...
- java多线程之yield,join,wait,sleep的区别
Java多线程之yield,join,wait,sleep的区别 Java多线程中,经常会遇到yield,join,wait和sleep方法.容易混淆他们的功能及作用.自己仔细研究了下,他们主要的区别 ...
- Java多线程之Runnable与Thread
Java多线程之Thread与Runnable 一.Thread VS Runnable 在java中可有两种方式实现多线程,一种是继承Thread类,一种是实现Runnable接口:Thread类和 ...
- JAVA多线程之UncaughtExceptionHandler——处理非正常的线程中止
JAVA多线程之UncaughtExceptionHandler——处理非正常的线程中止 背景 当单线程的程序发生一个未捕获的异常时我们可以采用try....catch进行异常的捕获,但是在多线程环境 ...
- java多线程之wait和notify协作,生产者和消费者
这篇直接贴代码了 package cn.javaBase.study_thread1; class Source { public static int num = 0; //假设这是馒头的数量 } ...
- Java——多线程之Lock锁
Java多线系列文章是Java多线程的详解介绍,对多线程还不熟悉的同学可以先去看一下我的这篇博客Java基础系列3:多线程超详细总结,这篇博客从宏观层面介绍了多线程的整体概况,接下来的几篇文章是对多线 ...
- Java线程之Timer
简述 java.util.Timer是一个定时器,用来调度线程在某个时间执行.在初始化Timer时,开启一个线程循环提取TaskQueue任务数组中的任务, 如果任务数组为空,线程等待直到添加任务: ...
随机推荐
- Ackerman
Ackerman 递归算法 一 . 问题描述及分析 图1 二 . 代码实现 package other; import java.io.BufferedWriter; import java.io.F ...
- Centos7安装InfluxDB1.7
Centos7安装InfluxDB1.7 本操作参照InfluxDB官网:InfuxDB 使用的Red Hat和CentOS用户可以安装InfluxDB最新的稳定版本 yum包管理器: cat < ...
- XVIII Open Cup named after E.V. Pankratiev. GP of Romania
A. Balance 不难发现确定第一行第一列后即可确定全部,列不等式单纯形求解线性规划即可. #include<cstdio> #include<algorithm> usi ...
- js 对时间进行判断 现在的时间是否在后台给的开始时间 和 结束时间 内 (时间格式为:2018-09-03 09:20:30)
function status(item){ let now = Date.parse(new Date()); let startString = Date.parse(new Date(Date. ...
- 1#Two Sum(qsort用法)
void*空类型指针,就好像暂时还没有确定类型,任何类型都可以赋给它.但是具体操作时一定要确定类型(如下,比较时先转Node) cmp返回一定是int,有-1,0,1三种,如果是1则第一个数要放在第二 ...
- HDFS基础配置
HADOOP-3.1.0-----HDFS基础配置 执行步骤:(1)配置集群(2)启动.测试集群增.删.查(3)执行wordcount案例 一.配置集群 1.在 hadoop-env.sh配置文件添加 ...
- 第6周Java学习任务
一.阅读ManagerTest 1.UML图 : 2.e.getSalary()到底是调用Manager类的还是Employee类的getSalary方法? stuff[0]中存的是Manager对象 ...
- 使用 JProbe 调试 Linux 内核(转)
https://liam.page/2018/04/28/debug-in-Linux-kernel-jprobe/
- eclipse spring-boot-mybatis 的记录
例子来源: https://gitee.com/lfalex/spring-boot-example.git spring-boot-mybatis 例子使用 mysql5.1.46 版本; 环境:e ...
- CodeForces #549 Div.2 ELynyrd Skynyrd 倍增算法
题目 这道题目实际上可以用动态规划来做. 对于每个区间,我们从右边边界,往左边走,如果能走n-1次,那说明以右边边界为起点存在一个题目中说的子链. 利用倍增算法,实际上倍增也是动态规划.f[i][j] ...