在jdk1.5之后,建议使用ScheduledExecutorService来代替timer执行任务,因为Timer定时任务抛出异常会导致其他任务终止,而ScheduledExecutorService不会。
如下代码,timerBug执行之后会发现t2终止,但ScheduleExecutorServiceDemo执行后发现t2仍正常运行。
package test;
import java.sql.Time;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class timerdemo {
public static void main(String[] args) {
final TimerTask t1=new TimerTask() {
@Override
public void run() {
int i=1/0;
}
};
final TimerTask t2=new TimerTask() {
@Override
public void run() {
System.out.println("t2 invoke.");
}
};
timerBug(t1,t2);
ScheduleExecutorServiceDemo(t1, t2);
}
private static void ScheduleExecutorServiceDemo(TimerTask t1, TimerTask t2) {
// t1即使抛异常也不会影响t2执行
ScheduledExecutorService executorService =new ScheduledThreadPoolExecutor(1);
executorService.schedule(t1,100, TimeUnit.MILLISECONDS);
executorService.scheduleAtFixedRate(t2,0,1000,TimeUnit.MILLISECONDS);
}
private static void timerBug(TimerTask t1,TimerTask t2) {
Timer time=new Timer();
time.schedule(t1,100);
// t1 任务抛异常会导致t2终止
time.scheduleAtFixedRate(t2,new Date(),1000);
}
}


网友评论