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:

public class TimerTest {
	private static final Timer timer1 = new Timer(true); 
	
	public static void main(String[] args) {
		timer1.schedule(new TimerTask(){
			@Override
			public void run() {
				System.out.println("执行定时任务...");
			}
		}, 0, 60000*1);
	}
}

 

ScheduledExecutorService:

public class ScheduleExecutor {
   private final ScheduledExecutorService scheduler = 
      Executors.newScheduledThreadPool(1);

   public void beepForMin() {
		final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(
				new Runnable() {
					public void run() {
						System.out.println("执行。。。");
					}
				}, 0, 10, SECONDS);
		
		scheduler.schedule(new Runnable() {
			public void run() {
				beeperHandle.cancel(true);
				System.exit(0);
			}
		}, 30, SECONDS);
	}
   
   
   public static void main(String[] args) {
	   ScheduleExecutor se = new ScheduleExecutor();
	   se.beepForMin();
   }
}


 


 

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值