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

问题描述 投票:0回答:1

在下面的代码中,注释掉会导致异常,这说明了我们已经调度或取消了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();
java multithreading executorservice timertask
1个回答
0
投票

@@ Slaw回答为:

因为Timer检查是否已取消TimerTask(即,此行为特定于Timer)。对于ScheduledExecutorServiceTimerTask只是一个Runnable

© www.soinside.com 2019 - 2024. All rights reserved.