为什么不能将TimerTask重用于另一个计时器,但是可以将已经使用的TimerTask重用于ScheduledExecutorService

时间:2019-05-06 06:23:55

标签: java multithreading executorservice timertask

在下面的代码中,注释掉的内容导致异常,这说明了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();

1 个答案:

答案 0 :(得分:0)

@Slaw回答为:

因为Timer会检查TimerTask是否已取消(即此行为特定于Timer)。对于ScheduledExecutorService来说,TimerTask仅仅是Runnable