Java定时器详解

java在jdk1.3中推出了定时器类Timer,而后在jdk1.5后由Dou Lea从新开发出了支持多线程的ScheduleThreadPoolExecutor,从后者的表现来看,可以考虑完全替代Timer了。

Timer与ScheduleThreadPoolExecutor对比:

1.

 

 Timer始于jdk1.3,其原理是利用一个TimerTask数组当作队列,将所有定时任务添加到此队列里面去。 然后启动一个线程,当队列为空时,此线程会阻塞,当队列里面有数据时,线程会去除一个TimerTask来判断

 是否到时间需要运行此任务,如果运行时间小于或等于当前时间时则开始运行任务。 由于其单线程的本质,所以会带来几个问题(详细代码在后面):

 第一,当我们添加到定时器中的任务比较耗时时,由于此定时器是单线程顺序执行定时器任务,所以会影响后续任务的按时执行。

 

Java代码   收藏代码
  1. //问题一示例:  
  2. m_timer.scheduleAtFixedRate(new TaskUseLongTime(), 10005000);  
  3. m_timer.scheduleAtFixedRate(new TaskNormal(), 50003000);  
  4.   
  5. 运行结果:  
  6. 14:44:29: timer is sleeping 10 seconds  
  7. 14:44:39: Task Normal executed  
  8. 14:44:39: timer is sleeping 10 seconds  
  9. 14:44:49: Task Normal executed  
  10. 14:44:49: Task Normal executed  
  11. 14:44:49: timer is sleeping 10 seconds  
  12.   
  13. 结果分析:TaskNormal任务无法保证3秒运行一次,其只能等待TaskUseLongTime运行结束后才可以。  

 

 

 第二,Timer中的线程仅仅会捕获InterruptedException异常,所以如果我们自定义的定时任务里面没有捕获可能出现的异常而导致异常抛出后,

 

Java代码   收藏代码
  1. //问题二示例:  
  2. m_timer.schedule(new TaskThrowException(), 1000);  
  3. m_timer.schedule(new TaskNormal(), 2000);  
  4.   
  5. 运行结果:  
  6. 14:47:37: Throw exception  
  7. Exception in thread "Timer-0" java.lang.RuntimeException  
  8.     at timer_test.TimerTest$TaskThrowException.run(TimerTest.java:85)  
  9.     at java.util.TimerThread.mainLoop(Timer.java:512)  
  10.     at java.util.TimerThread.run(Timer.java:462)  
  11.   
  12. 结果分析:  
  13. 当前一个任务抛出异常后,后面的TaskNormal任务无法继续运行  

 

 

 会导致我们的Timer线程停止,从而另后续的任务无法执行。

 第三,其无法处理多个同时发生的定时任务

 

Java代码   收藏代码
  1. //问题三示例:  
  2. m_timer.scheduleAtFixedRate(new TaskUseLongTime("timer1"), 100015000);  
  3. m_timer.scheduleAtFixedRate(new TaskUseLongTime("timer2"), 100015000);  
  4.   
  5. 运行结果:  
  6. 14:50:16: timer1 is sleeping 10 seconds  
  7. 14:50:26: timer2 is sleeping 10 seconds  
  8. 14:50:36: timer2 is sleeping 10 seconds  
  9.   
  10. 结果分析:  
  11. 我的启动时间均是1秒以后,但是timer1和timer2启动的时间明显不一致  

 

 

 

代码示例:

 

Java代码   收藏代码
  1. /** 
  2.  * @filename TimerTest.java 
  3.  * @date     2014-11-18  
  4.  */  
  5. package timer_test;  
  6.   
  7. import java.text.SimpleDateFormat;  
  8. import java.util.Date;  
  9. import java.util.Timer;  
  10. import java.util.TimerTask;  
  11.   
  12. public class TimerTest  
  13. {  
  14.     private final Timer m_timer = new Timer();  
  15.       
  16.     public static void main(String[] args)  
  17.     {  
  18.         new TimerTest().test();  
  19.     }  
  20.       
  21.     public void test()  
  22.     {  
  23.         //问题一示例:  
  24.         m_timer.scheduleAtFixedRate(new TaskUseLongTime(), 10005000);  
  25.         m_timer.scheduleAtFixedRate(new TaskNormal(), 50003000);  
  26.           
  27.         //问题二示例:  
  28. //      m_timer.schedule(new TaskThrowException(), 1000);  
  29. //      m_timer.schedule(new TaskNormal(), 2000);  
  30.           
  31.         //问题三示例:  
  32. //      m_timer.scheduleAtFixedRate(new TaskUseLongTime("timer1"), 1000, 5000);  
  33. //      m_timer.scheduleAtFixedRate(new TaskUseLongTime("timer2"), 1000, 5000);  
  34.   
  35.     }  
  36.       
  37.     private class TaskUseLongTime extends TimerTask  
  38.     {  
  39.         private String m_taskName = "timer";  
  40.         public TaskUseLongTime(){}  
  41.           
  42.         public TaskUseLongTime(String taskName)  
  43.         {  
  44.             m_taskName = taskName;  
  45.         }  
  46.         @Override  
  47.         public void run()  
  48.         {  
  49.             try  
  50.             {  
  51.                 System.out.println(getCurrentTime()+": "+m_taskName+" is sleeping 10 seconds");  
  52.                 Thread.sleep(10000);  
  53.             } catch (InterruptedException e)  
  54.             {  
  55.             }  
  56.         }  
  57.     }  
  58.       
  59.     private class TaskNormal extends TimerTask  
  60.     {  
  61.         @Override  
  62.         public void run()  
  63.         {  
  64.             System.out.println(getCurrentTime()+": Task Normal executed");  
  65.         }  
  66.     }  
  67.       
  68.     private class TaskThrowException extends TimerTask  
  69.     {  
  70.         @Override  
  71.         public void run()  
  72.         {  
  73.             System.out.println(getCurrentTime()+": Throw exception");  
  74.             throw new RuntimeException();  
  75.         }  
  76.     }  
  77.       
  78.     private String getCurrentTime()  
  79.     {  
  80.         return new SimpleDateFormat("HH:mm:ss").format(new Date());  
  81.     }  
  82. }  

 

 

2.ScheduleThreadPoolExecutor

 

ScheduleThreadPoolExecutor始于jdk1.5,是由Dou Lea先生编写的,其利用ThreadPoolExecutor和DelayQueue巧妙的结合完成了多线程定时器的实现,解决了Timer中由于单线程而导致的上述三个缺陷。

 

问题一中的问题是因为单线程顺序执行导致后续任务无法按时完成,我们看到多线程可以很容易的解决此问题,同时我们注意到TaskUseLongTime的执行时间为10s(请看后续代码),我们定时任务间隔是5秒,但是从结果中发现我们的任务执行间隔却是10秒,所以我们可以判断ScheduleThreadPoolExecutor是采用每线程每任务的模式工作的。

 

Java代码   收藏代码
  1. //问题一:  
  2. m_timer.scheduleAtFixedRate(new TaskUseLongTime(), 10005000, TimeUnit.MILLISECONDS);  
  3. m_timer.scheduleAtFixedRate(new TaskNormal(), 10005000, TimeUnit.MILLISECONDS);  
  4.   
  5. 运行结果:  
  6. 14:54:37: Task Normal executed  
  7. 14:54:37: timer is sleeping 10 seconds  
  8. 14:54:42: Task Normal executed  
  9. 14:54:47: Task Normal executed  
  10. 14:54:47: timer is sleeping 10 seconds  
  11. 14:54:52: Task Normal executed  

 

 

问题二中我们发现当抛出异常的任务执行后不影响其他任务的运行,同时我们发现在运行结果里面没有将我们的异常抛出,这是因为ScheduleThreadPoolExecutor类在执行完定时任务后会返回一个ScheduledFuture运行结果,不论结果是顺利完成还是有异常均会保存在这里。

 

 

Java代码   收藏代码
  1. //问题二:  
  2. m_timer.scheduleAtFixedRate(new TaskThrowException(), 10005000, TimeUnit.MILLISECONDS);  
  3. m_timer.scheduleAtFixedRate(new TaskNormal(), 10005000, TimeUnit.MILLISECONDS);  
  4.   
  5. 运行结果:  
  6. 14:58:36: Throw exception  
  7. 14:58:36: Task Normal executed  
  8. 14:58:41: Task Normal executed  
  9. 14:58:46: Task Normal executed  
  10. 14:58:51: Task Normal executed  
  11. 14:58:56: Task Normal executed  

 

 问题三由于是多线程所以我们可以保证我们的定时任务可以同时执行

Java代码   收藏代码
  1. //问题三:  
  2. m_timer.scheduleAtFixedRate(new TaskUseLongTime("timer1"), 10005000, TimeUnit.MILLISECONDS);  
  3. m_timer.scheduleAtFixedRate(new TaskUseLongTime("timer2"), 10005000, TimeUnit.MILLISECONDS);  
  4.   
  5. 运行结果:  
  6. 15:01:12: timer1 is sleeping 10 seconds  
  7. 15:01:12: timer2 is sleeping 10 seconds  
  8. 15:01:22: timer2 is sleeping 10 seconds  
  9. 15:01:22: timer1 is sleeping 10 seconds  
  10. 15:01:32: timer1 is sleeping 10 seconds  
  11. 15:01:32: timer2 is sleeping 10 seconds  

 

 详细代码:

Java代码   收藏代码
  1. /** 
  2.  * @filename ScheduleThreadPoolExecutorTest.java 
  3.  * @date     2014-11-18  
  4.  */  
  5. package timer_test;  
  6.   
  7. import java.text.SimpleDateFormat;  
  8. import java.util.Date;  
  9. import java.util.concurrent.Callable;  
  10. import java.util.concurrent.ScheduledThreadPoolExecutor;  
  11. import java.util.concurrent.TimeUnit;  
  12.   
  13. public class ScheduleThreadPoolExecutorTest  
  14. {  
  15.     private final ScheduledThreadPoolExecutor m_timer = new ScheduledThreadPoolExecutor(10);  
  16.       
  17.     public static void main(String[] args)  
  18.     {  
  19.         ScheduleThreadPoolExecutorTest timerTest = new ScheduleThreadPoolExecutorTest();  
  20.         timerTest.test();  
  21.           
  22.         try  
  23.         {  
  24.             Thread.sleep(100000);  
  25.         } catch (InterruptedException e)  
  26.         {  
  27.         }finally  
  28.         {  
  29.             timerTest.shutdown();  
  30.         }  
  31.     }  
  32.       
  33.     public void shutdown()  
  34.     {  
  35.         m_timer.shutdown();  
  36.     }  
  37.       
  38.     public void test()  
  39.     {  
  40.         //问题一:  
  41. //      m_timer.scheduleAtFixedRate(new TaskUseLongTime(), 1000, 5000, TimeUnit.MILLISECONDS);  
  42. //      m_timer.scheduleAtFixedRate(new TaskNormal(), 1000, 5000, TimeUnit.MILLISECONDS);  
  43.           
  44.         //问题二:  
  45. //      m_timer.scheduleAtFixedRate(new TaskThrowException(), 1000, 5000, TimeUnit.MILLISECONDS);  
  46. //      m_timer.scheduleAtFixedRate(new TaskNormal(), 1000, 5000, TimeUnit.MILLISECONDS);  
  47.           
  48.         //问题三:  
  49.         m_timer.scheduleAtFixedRate(new TaskUseLongTime("timer1"), 10005000, TimeUnit.MILLISECONDS);  
  50.         m_timer.scheduleAtFixedRate(new TaskUseLongTime("timer2"), 10005000, TimeUnit.MILLISECONDS);  
  51.           
  52.     }  
  53.       
  54.     private class TaskUseLongTime implements Callable<Integer>, Runnable  
  55.     {  
  56.         private String m_taskName = "timer";  
  57.         private TaskUseLongTime(){}  
  58.           
  59.         private TaskUseLongTime(String taskName)  
  60.         {  
  61.             m_taskName = taskName;  
  62.         }  
  63.           
  64.         public void run()  
  65.         {  
  66.             try  
  67.             {  
  68.                 System.out.println(getCurrentTime()+": "+m_taskName+" is sleeping 10 seconds");  
  69.                 Thread.sleep(10000);  
  70.             } catch (InterruptedException e)  
  71.             {  
  72.             }  
  73.         }  
  74.   
  75.         public Integer call() throws Exception  
  76.         {  
  77.             run();  
  78.             return 0;  
  79.         }  
  80.     }  
  81.       
  82.     @SuppressWarnings("unused")  
  83.     private class TaskNormal implements Callable<Integer>, Runnable  
  84.     {  
  85.           
  86.         public Integer call() throws Exception  
  87.         {  
  88.             run();  
  89.             return 0;  
  90.         }  
  91.   
  92.         public void run()  
  93.         {  
  94.             System.out.println(getCurrentTime()+": Task Normal executed");  
  95.         }  
  96.     }  
  97.       
  98.     @SuppressWarnings("unused")  
  99.     private class TaskThrowException implements Callable<Integer>, Runnable  
  100.     {  
  101.         public Integer call() throws Exception  
  102.         {  
  103.             System.out.println(getCurrentTime()+": Throw exception");  
  104.             throw new RuntimeException();  
  105.         }  
  106.   
  107.         public void run()  
  108.         {  
  109.             System.out.println(getCurrentTime()+": Throw exception");  
  110.             throw new RuntimeException();  
  111.         }  
  112.     }  
  113.       
  114.       
  115.     private String getCurrentTime()  
  116.     {  
  117.         return new SimpleDateFormat("HH:mm:ss").format(new Date());  
  118.     }  
  119. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值