您的位置:首页 > 编程语言 > Java开发

使用java自带的定时任务ScheduledThreadPoolExecutor

2018-04-24 19:05 351 查看

ScheduledThreadPoolExecutor是ThreadPoolExecutor的子类;

JDK api里是这么说的:

 

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

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

---------------

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

但是Timer和TimerTask存在一些缺陷:

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

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

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

 

 

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 }

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: