timer 和 ScheduledThreadExecutor定时

java.util.Timer计时器有管理任务延迟执行("如1000ms后执行任务")以及周期性执行("如每500ms执行一次该任务")。但是,Timer存在一些缺陷,因此你应该考虑使用ScheduledThreadPoolExecutor作为代替品,Timer对调度的支持是基于绝对时间,而不是相对时间的,由此任务对系统时钟的改变是敏感的;ScheduledThreadExecutor只支持相对时间。

    Timer的另一个问题在于,如果TimerTask抛出未检查的异常,Timer将会产生无法预料的行为。Timer线程并不捕获异常,所以TimerTask抛出的未检查的异常会终止timer线程。这种情况下,Timer也不会再重新恢复线程的执行了;它错误的认为整个Timer都被取消了。此时,已经被安排但尚未执行的TimerTask永远不会再执行了,新的任务也不能被调度了。

  1. package com.bill99.test;   
  2.   
  3. import java.util.Timer;   
  4. import java.util.TimerTask;   
  5.   
  6. public class TimerTest {   
  7.     private Timer timer = new Timer();   
  8.     //启动计时器   
  9.     public void lanuchTimer(){   
  10.         timer.schedule(new TimerTask(){   
  11.             public void run() {   
  12.                 throw new RuntimeException();   
  13.             }   
  14.         }, 1000*3500);   
  15.     }   
  16.     //向计时器添加一个任务   
  17.     public void addOneTask(){   
  18.         timer.schedule(new TimerTask(){   
  19.             public void run(){   
  20.                 System.out.println("hello world");   
  21.             }   
  22.         }, 1000*1,1000*5);   
  23.     }   
  24.        
  25.     public static void main(String[] args) throws Exception {   
  26.         TimerTest test = new TimerTest();   
  27.         test.lanuchTimer();   
  28.         Thread.sleep(1000*5);//5秒钟之后添加一个新任务   
  29.         test.addOneTask();   
  30.     }   
  31. }  
  32.  

  33. 运行该程序,Timer会抛出一个RumtimeExceptionjava.lang.IllegalStateException:Timer already cancelled.

    常言道,真是祸不单行,Timer还将它的问题传染给下一个倒霉的调用者,这个调用者原本试图提交一个TimerTask的,你可能希望程序会一直运行下去,然而实际情况如程序所示5秒钟后就中止了,还伴随着一个异常,异常的消息是"Timer already cancelled"。ScheduledThreadPoolExector妥善地处理了这个异常的任务,所以说在java5.0或更高的JDK中,几乎没有理由再使用Timer了。

     用ScheduledThreadPoolExector改进后的例子

    • package com.bill99.test;   
    •   
    • import java.util.concurrent.Executors;   
    • import java.util.concurrent.ScheduledExecutorService;   
    • import java.util.concurrent.TimeUnit;   
    •   
    • public class ScheduledExecutorTest {   
    •     //线程池能按时间计划来执行任务,允许用户设定计划执行任务的时间,int类型的参数是设定   
    •     //线程池中线程的最小数目。当任务较多时,线程池可能会自动创建更多的工作线程来执行任务   
    •     public ScheduledExecutorService scheduExec = Executors.newScheduledThreadPool(1);   
    •     //启动计时器   
    •     public void lanuchTimer(){   
    •         Runnable task = new Runnable() {   
    •             public void run() {   
    •                 throw new RuntimeException();   
    •             }   
    •         };   
    •         scheduExec.scheduleWithFixedDelay(task, 1000*51000*10, TimeUnit.MILLISECONDS);   
    •     }   
    •     //添加新任务   
    •     public void addOneTask(){   
    •         Runnable task = new Runnable() {   
    •             public void run() {   
    •                 System.out.println("welcome to china");   
    •             }   
    •         };   
    •         scheduExec.scheduleWithFixedDelay(task, 1000*11000, TimeUnit.MILLISECONDS);   
    •     }   
    •        
    •     public static void main(String[] args) throws Exception {   
    •         ScheduledExecutorTest test = new ScheduledExecutorTest();   
    •         test.lanuchTimer();   
    •         Thread.sleep(1000*5);//5秒钟之后添加新任务   
    •         test.addOneTask();   
    •     }   
    • ScheduledExecutorService接口
      在ExecutorService的基础上,ScheduledExecutorService提供了按时间安排执行任务的功能,它提供的方法主要有:
      schedule(task,initDelay):安排所提交的Callable或Runnable任务在initDelay指定的时间后执行。
      scheduleAtFixedRate():安排所提交的Runnable任务按指定的间隔重复执行
      scheduleWithFixedDelay():安排所提交的Runnable任务在每次执行完后,等待delay所指定的时间后重复执行。
      代码:ScheduleExecutorService的例子
      import java.util.concurrent.Callable;
      import java.util.concurrent.ExecutionException;
      import java.util.concurrent.Executors;
      import java.util.concurrent.ScheduledExecutorService;
      import java.util.concurrent.ScheduledFuture;
      import java.util.concurrent.TimeUnit;

      public class ScheduledExecutorServiceTest
      {
             public static void main(String[] args) throws InterruptedException,ExecutionException
             {
                    //*1
                     ScheduledExecutorService service=Executors.newScheduledThreadPool(2);
                     //*2
                     Runnable task1=new Runnable()
                     {
                          public void run()
                          {
                             System.out.println("Taskrepeating.");
                          }
                     };
                     //*3
                     final ScheduledFuture future1=service.scheduleAtFixedRate(task1,0,1,TimeUnit.SECONDS);
                     //*4
                     ScheduledFuture future2=service.schedule(new Callable()
                   {
                          public String call()
                          {
                                  future1.cancel(true);
                                  return "taskcancelled!";
                          }
                     },10,TimeUnit.SECONDS);
                     System.out.println(future2.get());
          //*5
          service.shutdown();
         }
      }

      这个例子有两个任务,第一个任务每隔一秒打印一句“Taskrepeating”,第二个任务在5秒钟后取消第一个任务。

     

     

     

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值