ExecutorService取代Timer.docx
- 文档编号:18403994
- 上传时间:2023-08-16
- 格式:DOCX
- 页数:9
- 大小:18.05KB
ExecutorService取代Timer.docx
《ExecutorService取代Timer.docx》由会员分享,可在线阅读,更多相关《ExecutorService取代Timer.docx(9页珍藏版)》请在冰点文库上搜索。
ExecutorService取代Timer
《Java并发编程实战》一书提到的用ExecutorService取代JavaTimer有几个理由,我认为其中最重要的理由是:
如果TimerTask抛出未检查的异常,Timer将会产生无法预料的行为。
Timer线程并不捕获异常,所以TimerTask抛出的未检查的异常会终止timer线程。
这种情况下,Timer也不会再重新恢复线程的执行了;它错误的认为整个Timer都被取消了。
此时,已经被安排但尚未执行的TimerTask永远不会再执行了,新的任务也不能被调度了。
stackoverflow上也有关于此问题的讨论:
Timer的问题:
Java代码
1packagecom.ljn.timer;
2
3importjava.util.Date;
4importjava.util.Timer;
5
6/**
7*@authorlijinnan
8*@date:
2013-11-25下午3:
27:
43
9*/
10publicclassTimerException{
11
12publicstaticvoidmain(String[]args){
13System.out.println("start:
"+newDate());
14Timertimer=newTimer();
15intdelay=1000;
16intperiod=2000;
17timer.schedule(newOKTask(),delay*2,period);//"OKTask"doesnotgetchancetoexecute
18timer.schedule(newErrorTask(),delay,period);//exceptionin"ErrorTask"willterminatetheTimer
19}
20
21/*输出:
22start:
MonNov2517:
49:
53CST2013
23ErrorTaskisexecuting...
24error:
MonNov2517:
49:
55CST2013
25Exceptioninthread"Timer-0"java.lang.RuntimeException:
somethingwrong
26atcom.ljn.timer.ErrorTask.run(ErrorTask.java:
14)
27*/
28
29}
用ExecutorService则正常:
Java代码
30packagecom.ljn.timer;
31
32importjava.util.Date;
33importjava.util.concurrent.Executors;
34importjava.util.concurrent.ScheduledExecutorService;
35importjava.util.concurrent.TimeUnit;
36
37/**
38*@authorlijinnan
39*@date:
2013-11-25下午3:
35:
39
40*/
41publicclassScheduledExecutorServiceTest{
42
43publicstaticScheduledExecutorServicescheduledExecutorService=Executors.newScheduledThreadPool
(2);
44
45publicstaticvoidmain(String[]args){
46System.out.println("start:
"+newDate());
47ErrorTaskerrorTask=newErrorTask();
48OKTaskokTask=newOKTask();
49intdelay=1000;
50intperiod=2000;
51scheduledExecutorService.scheduleAtFixedRate(errorTask,delay,period,TimeUnit.MILLISECONDS);//"ErrorTask"throwsExceptionandthenstopes.
52scheduledExecutorService.scheduleAtFixedRate(okTask,delay*2,period,TimeUnit.MILLISECONDS);//"OKTask"isexecutedperiodically,notaffectedby"ErrorTask"
53
54//scheduledExecutorService.shutdown();
55}
56
57/*
58start:
MonNov2517:
54:
22CST2013
59ErrorTaskisexecuting...
60erroroccurs:
MonNov2517:
54:
24CST2013
61OKTaskisexecuted:
MonNov2517:
54:
24CST2013
62OKTaskisexecuted:
MonNov2517:
54:
26CST2013
63OKTaskisexecuted:
MonNov2517:
54:
28CST2013
64......
65*/
66
67}
另外开发中常常会让任务在每天的指定时间点运行,示例如下:
Java代码
68packagecom.ljn.timer;
69
70importjava.util.Date;
71importjava.util.concurrent.Executors;
72importjava.util.concurrent.ScheduledExecutorService;
73importjava.util.concurrent.TimeUnit;
74
75/**
76*@authorlijinnan
77*@date:
2013-11-25下午5:
18:
55
78*/
79publicclassFixedDatetimeTaskTest{
80
81publicstaticScheduledExecutorServicescheduledExecutorService=Executors.newScheduledThreadPool
(1);
82
83publicstaticvoidmain(String[]args)throwsException{
84System.out.println("start:
"+newDate());
85
86//每天的02:
30:
00执行任务
87longdelay=Helper.calcDelay(2,30,0);
88longperiod=Helper.ONE_DAY;
89scheduledExecutorService.scheduleAtFixedRate(newOKTask(),delay,period,TimeUnit.MILLISECONDS);
90}
91
92}
文章中用到的其他类:
Java代码
93packagecom.ljn.timer;
94
95importjava.util.Date;
96importjava.util.TimerTask;
97
98publicclassErrorTaskextendsTimerTask{
99
100@Override
101publicvoidrun(){
102try{
103System.out.println("ErrorTaskisexecuting...");
104Thread.sleep(1000);
105System.out.println("erroroccurs:
"+newDate());
106thrownewRuntimeException("somethingwrong");
107}catch(InterruptedExceptione){
108}
109}
110
111}
Java代码
112packagecom.ljn.timer;
113
114importjava.util.Date;
115importjava.util.TimerTask;
116
117
118publicclassOKTaskextendsTimerTask{
119
120@Override
121publicvoidrun(){
122System.out.println("OKTaskisexecuted:
"+newDate());
123}
124}
Java代码
125packagecom.ljn.timer;
126
127importorg.joda.time.DateTime;
128
129/**
130*@authorlijinnan
131*@date:
2013-11-25下午5:
17:
40
132*/
133publicclassHelper{
134
135privateHelper(){}
136
137publicstaticfinallongONE_DAY=60*60*24;
138
139publicstaticlongcalcDelay(inthour,intminute,intsecond){
140if(!
(0<=hour&&hour<=23&&0<=minute&&minute<=59&&0<=second&&second<=59)){
141thrownewIllegalArgumentException();
142}
143returncalcDelay(fixed(hour,minute,second));
144}
145
146privatestaticlongcalcDelay(DateTimetargetDatetimeOfToday){
147longdelay=0;
148DateTimenow=newDateTime();
149
150//时间点已过,只好延时到明天的这个时间点再执行
151if(now.isAfter(targetDatetimeOfToday)){
152delay=now.plusDays
(1).getMillis()-now.getMillis();
153
154//时间点未到
155}else{
156delay=targetDatetimeOfToday.getMillis()-now.getMillis();
157}
158
159returndelay;
160}
161
162/**
163*返回这样一个DateTime对象:
164*1.日期为今天
165*2.时分秒为参数指定的值
166*@paramhour0-23
167*@paramminute0-59
168*@paramsecond0-59
169*@return
170*/
171privatestaticDateTimefixed(inthour,intminute,intsecond){
172
173returnnewDateTime()
174.withHourOfDay(hour).withMinuteOfHour(minute).withSecondOfMinute(second);
175}
176
177}
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- ExecutorService 取代 Timer