使用java自带的定时任务ScheduledThreadPoolExecutor

ScheduledThreadPoolExecutor是ThreadPoolExecutor的子类;html

JDK api里是这么说的:java

 

ThreadPoolExecutor,它可另行安排在给定的延迟后运行命令,或者按期执行命令。须要多个辅助线程时,或者要求 ThreadPoolExecutor 具备额外的灵活性或功能时,此类要优于 Timerapi

一旦启用已延迟的任务就执行它,可是有关什么时候启用,启用后什么时候执行则没有任何实时保证。按照提交的先进先出 (FIFO) 顺序来启用那些被安排在同一执行时间的任务。ide

---------------spa

平时咱们在执行一个定时任务时,会采用Time,和TimeTask来组合处理;.net

可是Timer和TimerTask存在一些缺陷:线程

1:Timer只建立了一个线程。当你的任务执行的时间超过设置的延时时间将会产生一些问题。code

2:Timer建立的线程没有处理异常,所以一旦抛出非受检异常,该线程会当即终止。orm

JDK 5.0之后推荐使用ScheduledThreadPoolExecutor。该类属于Executor Framework,它除了能处理异常外,还能够建立多个线程解决上面的问题htm

 

 

复制代码
 1 package timer;
 2 
 3 import java.text.SimpleDateFormat;
 4 import java.util.Date;
 5 import java.util.concurrent.ScheduledThreadPoolExecutor;
 6 import java.util.concurrent.TimeUnit;
 7 
 8 public class Test
 9 {
10     static ScheduledThreadPoolExecutor stp = null;
11     static int index;
12     
13     private static String getTimes() {  
14         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");  
15         Date date = new Date();  
16         date.setTime(System.currentTimeMillis());  
17         return format.format(date);  
18     } 
19     
20     
21     private static class MyTask implements Runnable {  
22         
23         @Override  
24         public void run() {  
25             index++;  
26             System.out.println("2= " + getTimes()+" "  +index);  
27 //            if(index >=10){  
28 //                stp.shutdown();  
29 //                if(stp.isShutdown()){  
30 //                    System.out.println("中止了????");
31 //                } 
32 //            }
33         }
34     }
35     public static void main(String[] args)
36     {
37         stp = new ScheduledThreadPoolExecutor(5);
38         MyTask mytask = new MyTask();
39         //mytask为线程,2是首次执行的延迟时间,最后一个参数为时间单位
40 //        stp.schedule(mytask, 2, TimeUnit.SECONDS);
41         // 首次执行延迟2秒,以后的执行周期是1秒
42 //        stp.scheduleAtFixedRate(mytask, 2, 1,TimeUnit.SECONDS );
43         //首次执行延迟2秒,以后从上一次任务结束到下一次任务开始时1秒
44         stp.scheduleWithFixedDelay(mytask, 2, 1, TimeUnit.SECONDS);
45         
46     }
47 
48 }
复制代码
相关文章
相关标签/搜索