1、Timer管理延时任务的缺陷

a、以前在项目中也经常使用定时器,比如每隔一段时间清理项目中的一些垃圾文件,每个一段时间进行数据清洗;然而Timer是存在一些缺陷的,因为Timer在执行定时任务时只会创建一个线程,所以如果存在多个任务,且任务时间过长,超过了两个任务的间隔时间,会发生一些缺陷:下面看例子:

Timer的源码:

  1. public class Timer {
  2. /**
  3. * The timer task queue.  This data structure is shared with the timer
  4. * thread.  The timer produces tasks, via its various schedule calls,
  5. * and the timer thread consumes, executing timer tasks as appropriate,
  6. * and removing them from the queue when they're obsolete.
  7. */
  8. private TaskQueue queue = new TaskQueue();
  9. /**
  10. * The timer thread.
  11. */
  12. private TimerThread thread = new TimerThread(queue);

TimerThread是Thread的子类,可以看出内部只有一个线程。下面看个例子:

  1. package com.zhy.concurrency.timer;
  2. import java.util.Timer;
  3. import java.util.TimerTask;
  4. public class TimerTest
  5. {
  6. private static long start;
  7. public static void main(String[] args) throws Exception
  8. {
  9. TimerTask task1 = new TimerTask()
  10. {
  11. @Override
  12. public void run()
  13. {
  14. System.out.println("task1 invoked ! "
  15. + (System.currentTimeMillis() - start));
  16. try
  17. {
  18. Thread.sleep(3000);
  19. } catch (InterruptedException e)
  20. {
  21. e.printStackTrace();
  22. }
  23. }
  24. };
  25. TimerTask task2 = new TimerTask()
  26. {
  27. @Override
  28. public void run()
  29. {
  30. System.out.println("task2 invoked ! "
  31. + (System.currentTimeMillis() - start));
  32. }
  33. };
  34. Timer timer = new Timer();
  35. start = System.currentTimeMillis();
  36. timer.schedule(task1, 1000);
  37. timer.schedule(task2, 3000);
  38. }
  39. }

定义了两个任务,预计是第一个任务1s后执行,第二个任务3s后执行,但是看运行结果:

  1. task1 invoked ! 1000
  2. task2 invoked ! 4000

task2实际上是4后才执行,正因为Timer内部是一个线程,而任务1所需的时间超过了两个任务间的间隔导致。下面使用ScheduledThreadPool解决这个问题:

  1. package com.zhy.concurrency.timer;
  2. import java.util.TimerTask;
  3. import java.util.concurrent.Executors;
  4. import java.util.concurrent.ScheduledExecutorService;
  5. import java.util.concurrent.TimeUnit;
  6. public class ScheduledThreadPoolExecutorTest
  7. {
  8. private static long start;
  9. public static void main(String[] args)
  10. {
  11. /**
  12. * 使用工厂方法初始化一个ScheduledThreadPool
  13. */
  14. ScheduledExecutorService newScheduledThreadPool = Executors
  15. .newScheduledThreadPool(2);
  16. TimerTask task1 = new TimerTask()
  17. {
  18. @Override
  19. public void run()
  20. {
  21. try
  22. {
  23. System.out.println("task1 invoked ! "
  24. + (System.currentTimeMillis() - start));
  25. Thread.sleep(3000);
  26. } catch (Exception e)
  27. {
  28. e.printStackTrace();
  29. }
  30. }
  31. };
  32. TimerTask task2 = new TimerTask()
  33. {
  34. @Override
  35. public void run()
  36. {
  37. System.out.println("task2 invoked ! "
  38. + (System.currentTimeMillis() - start));
  39. }
  40. };
  41. start = System.currentTimeMillis();
  42. newScheduledThreadPool.schedule(task1, 1000, TimeUnit.MILLISECONDS);
  43. newScheduledThreadPool.schedule(task2, 3000, TimeUnit.MILLISECONDS);
  44. }
  45. }

输出结果:

  1. task1 invoked ! 1001
  2. task2 invoked ! 3001

符合我们的预期结果。因为ScheduledThreadPool内部是个线程池,所以可以支持多个任务并发执行。

2、Timer当任务抛出异常时的缺陷

如果TimerTask抛出RuntimeException,Timer会停止所有任务的运行:

  1. package com.zhy.concurrency.timer;
  2. import java.util.Date;
  3. import java.util.Timer;
  4. import java.util.TimerTask;
  5. public class ScheduledThreadPoolDemo01
  6. {
  7. public static void main(String[] args) throws InterruptedException
  8. {
  9. final TimerTask task1 = new TimerTask()
  10. {
  11. @Override
  12. public void run()
  13. {
  14. throw new RuntimeException();
  15. }
  16. };
  17. final TimerTask task2 = new TimerTask()
  18. {
  19. @Override
  20. public void run()
  21. {
  22. System.out.println("task2 invoked!");
  23. }
  24. };
  25. Timer timer = new Timer();
  26. timer.schedule(task1, 100);
  27. timer.scheduleAtFixedRate(task2, new Date(), 1000);
  28. }
  29. }

上面有两个任务,任务1抛出一个运行时的异常,任务2周期性的执行某个操作,输出结果:

  task2 invoked!

  1. Exception in thread "Timer-0" java.lang.RuntimeException
  2. at com.zhy.concurrency.timer.ScheduledThreadPoolDemo01$1.run(ScheduledThreadPoolDemo01.java:24)
  3. at java.util.TimerThread.mainLoop(Timer.java:512)
  4. at java.util.TimerThread.run(Timer.java:462)

由于任务1的一次,任务2也停止运行了。。。下面使用ScheduledExecutorService解决这个问题:

  1. package com.zhy.concurrency.timer;
  2. import java.util.Date;
  3. import java.util.Timer;
  4. import java.util.TimerTask;
  5. import java.util.concurrent.Executors;
  6. import java.util.concurrent.ScheduledExecutorService;
  7. import java.util.concurrent.TimeUnit;
  8. public class ScheduledThreadPoolDemo01
  9. {
  10. public static void main(String[] args) throws InterruptedException
  11. {
  12. final TimerTask task1 = new TimerTask()
  13. {
  14. @Override
  15. public void run()
  16. {
  17. throw new RuntimeException();
  18. }
  19. };
  20. final TimerTask task2 = new TimerTask()
  21. {
  22. @Override
  23. public void run()
  24. {
  25. System.out.println("task2 invoked!");
  26. }
  27. };
  28. ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
  29. pool.schedule(task1, 100, TimeUnit.MILLISECONDS);
  30. pool.scheduleAtFixedRate(task2, 0 , 1000, TimeUnit.MILLISECONDS);
  31. }
  32. }

代码基本一致,但是ScheduledExecutorService可以保证,task1出现异常时,不影响task2的运行:

  1. task2 invoked!
  2. task2 invoked!
  3. task2 invoked!
  4. task2 invoked!
  5. task2 invoked!<span style="font-family: Arial, Helvetica, sans-serif;">...</span>

3、Timer执行周期任务时依赖系统时间

Timer执行周期任务时依赖系统时间,如果当前系统时间发生变化会出现一些执行上的变化,ScheduledExecutorService基于时间的延迟,不会由于系统时间的改变发生执行变化。

上述,基本说明了在以后的开发中尽可能使用ScheduledExecutorService(JDK1.5以后)替代Timer。

Java 多线程之Timer与ScheduledExecutorService的更多相关文章

  1. Java多线程之ConcurrentSkipListMap深入分析(转)

    Java多线程之ConcurrentSkipListMap深入分析   一.前言 concurrentHashMap与ConcurrentSkipListMap性能测试 在4线程1.6万数据的条件下, ...

  2. JAVA多线程之wait/notify

    本文主要学习JAVA多线程中的 wait()方法 与 notify()/notifyAll()方法的用法. ①wait() 与 notify/notifyAll 方法必须在同步代码块中使用 ②wait ...

  3. JAVA多线程之volatile 与 synchronized 的比较

    一,volatile关键字的可见性 要想理解volatile关键字,得先了解下JAVA的内存模型,Java内存模型的抽象示意图如下: 从图中可以看出: ①每个线程都有一个自己的本地内存空间--线程栈空 ...

  4. java多线程之yield,join,wait,sleep的区别

    Java多线程之yield,join,wait,sleep的区别 Java多线程中,经常会遇到yield,join,wait和sleep方法.容易混淆他们的功能及作用.自己仔细研究了下,他们主要的区别 ...

  5. Java多线程之Runnable与Thread

    Java多线程之Thread与Runnable 一.Thread VS Runnable 在java中可有两种方式实现多线程,一种是继承Thread类,一种是实现Runnable接口:Thread类和 ...

  6. JAVA多线程之UncaughtExceptionHandler——处理非正常的线程中止

    JAVA多线程之UncaughtExceptionHandler——处理非正常的线程中止 背景 当单线程的程序发生一个未捕获的异常时我们可以采用try....catch进行异常的捕获,但是在多线程环境 ...

  7. java多线程之wait和notify协作,生产者和消费者

    这篇直接贴代码了 package cn.javaBase.study_thread1; class Source { public static int num = 0; //假设这是馒头的数量 } ...

  8. Java——多线程之Lock锁

    Java多线系列文章是Java多线程的详解介绍,对多线程还不熟悉的同学可以先去看一下我的这篇博客Java基础系列3:多线程超详细总结,这篇博客从宏观层面介绍了多线程的整体概况,接下来的几篇文章是对多线 ...

  9. Java线程之Timer

    简述 java.util.Timer是一个定时器,用来调度线程在某个时间执行.在初始化Timer时,开启一个线程循环提取TaskQueue任务数组中的任务, 如果任务数组为空,线程等待直到添加任务: ...

随机推荐

  1. ISP PIPLINE(零) 知识综述预热之光学概念篇

    1.光学成像关系如下:这是我看到最清晰的易懂的数学关系图 2.上面的知识了解完,camera应用的知识就是Autofocus技术,自动对焦 马达的起始位置一般在焦距处,由上面光学数学关系可知,焦距处可 ...

  2. 我的 FPGA 学习历程(05)—— 使用 Modelsim 仿真工具

    在第 3 篇中讲到了如何使用图形进行仿真激励输入,图形输入法尽管简单易学,但如若要求复杂的仿真输入激励.较长的仿真时间或是要求打印输出信息乃至输出文件日志则显得不够用了. 本篇以上一篇的 3-8 译码 ...

  3. luo3372线段树模板的分块做法

    题目大意 请你维护一个有n个元素的整数序列,要求支持区间查询&区间修改 对于100%的数据,\(1<=n<=10^5\) 分析 正常做法是线段树维护区间修改.区间查询,今天我要讲的 ...

  4. css 绘制三角形

    <!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  5. [LeetCode] Shortest Distance to a Character 到字符的最短距离

    Given a string S and a character C, return an array of integers representing the shortest distance f ...

  6. hdfs directory item limit - (dfs.namenode.fs-limits.max-directory-items)

    // :: WARN scheduler.TaskSetManager: Lost task , emr-worker-.cluster-, executor ): org.apache.hadoop ...

  7. C++ 编译发现 error C2146: syntax error : missing ';' before identifier 'm_ctrlserver'

    解决这个问题的根源是重复包含了头文件

  8. day29 二十九、元类、单例

    一.eval.exec内置函数 1.eval函数 eval内置函数的使用场景: ①执行字符串会得到相应的执行结果 ②一般用于类型转换得到dict.list.tuple等 2.exec函数 exec应用 ...

  9. CodeForces 1143A The Doors

    The Doors 签到题 #include <iostream> using namespace std; int a[200005]; int main() { int n; scan ...

  10. 20175320 2018-2019-2 《Java程序设计》第9周学习总结

    20175320 2018-2019-2 <Java程序设计>第9周学习总结 教材学习内容总结 本周学习了教材的第十一章的内容,在这章中介绍了JDBC与Mysql数据库,通过本章我了解到了 ...