在下面的代码中,注释掉的内容导致异常,这说明了timerTask2
已被调度或取消,但是,如果执行者在注释掉的部分下面的代码中重复使用和运行,则什么也无法阻止。怎么解释?
Timer timer2 = new Timer();
TimerTask timerTask2 = new ThreadTest6();
delay = 1000 L;
long period = 1000 L;
timer2.scheduleAtFixedRate(timerTask2, delay, period);
try {
Thread.sleep(10500);
} catch (InterruptedException e) {
e.printStackTrace();
}
timer2.purge();
timer2.cancel();
timerTask2.cancel();
// Timer timer3=new Timer();
// System.out.println("Task reuse");
// System.out.println();
//
// timer3.scheduleAtFixedRate(timerTask2, delay, period);
//
// try {
// Thread.sleep(1500);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
System.out.println("At the executor service");
System.out.println();
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
delay = 1000 L;
period = 1000 L;
executor.scheduleAtFixedRate(timerTask2, delay, period, TimeUnit.MILLISECONDS);
try {
Thread.sleep(delay + period * 3);
} catch (InterruptedException e) {
e.printStackTrace();
}
executor.shutdown();
答案 0 :(得分:0)
@Slaw回答为:
因为Timer
会检查TimerTask
是否已取消(即此行为特定于Timer
)。对于ScheduledExecutorService
来说,TimerTask
仅仅是Runnable