Timer与ScheduledExecutorService 的使用和区别

Timer和ScheduledExecutorService都可以用来做定时任务,有管理任务延迟执行("如1000ms后执行任务")以及周期性执行("如每500ms执行一次该任务")。但至从JDK1.5之后,建议采用ScheduledExecutorService。

原因如下:

1、Timer对调度的支持是基于绝对时间,而不是相对时间的,由此任务对系统时钟的改变是敏感的;但ScheduledThreadExecutor只支持相对时间。

2、如果TimerTask抛出未检查的异常,Timer将会产生无法预料的行为。Timer线程并不捕获异常,所以 TimerTask抛出的未检查的异常会终止timer线程。此时,已经被安排但尚未执行的TimerTask永远不会再执行了,新的任务也不能被调度了。

3、Timer里面的任务如果执行时间太长,会独占Timer对象,使得后面的任务无法几时的执行 ,ScheduledExecutorService不会出现Timer的问题(除非你只搞一个单线程池的任务区)

 

Timer:

[java]  view plain copy print ?
  1. public class TimerTest {  
  2.     private static final Timer timer1 = new Timer(true);   
  3.       
  4.     public static void main(String[] args) {  
  5.         timer1.schedule(new TimerTask(){  
  6.             @Override  
  7.             public void run() {  
  8.                 System.out.println("执行定时任务...");  
  9.             }  
  10.         }, 060000*1);  
  11.     }  
  12. }  

 

ScheduledExecutorService:

[java]  view plain copy print ?
  1. public class ScheduleExecutor {  
  2.    private final ScheduledExecutorService scheduler =   
  3.       Executors.newScheduledThreadPool(1);  
  4.   
  5.    public void beepForMin() {  
  6.         final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(  
  7.                 new Runnable() {  
  8.                     public void run() {  
  9.                         System.out.println("执行。。。");  
  10.                     }  
  11.                 }, 010, SECONDS);  
  12.           
  13.         scheduler.schedule(new Runnable() {  
  14.             public void run() {  
  15.                 beeperHandle.cancel(true);  
  16.                 System.exit(0);  
  17.             }  
  18.         }, 30, SECONDS);  
  19.     }  
  20.      
  21.      
  22.    public static void main(String[] args) {  
  23.        ScheduleExecutor se = new ScheduleExecutor();  
  24.        se.beepForMin();  
  25.    }  
  26. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值