程序为什么要等待schedule()完成,但不等待scheduleWithFixedDelay()?
问题描述:
下面的代码:程序为什么要等待schedule()完成,但不等待scheduleWithFixedDelay()?
ScheduledExecutorService service = null;
try {
service = Executors.newSingleThreadScheduledExecutor();
Runnable task1 =() -> System.out.println("Executed only once");
Runnable task2 =() -> System.out.println("Executed repeatedly");
service.schedule(task1, 5, TimeUnit.SECONDS);
service.scheduleWithFixedDelay(task2, 6, 2, TimeUnit.SECONDS);
} finally {
if (service != null) {
service.shutdown();
}
}
当执行上面的代码程序等待5秒至运行时间表(),但之后它完成,而无需运行scheduleWithFixedDelay()。
我怀疑原因是schedule()与scheduleWithFixedDelay()同步执行,但我没有在文档中找到有利于此的参数。
答
这是一个微妙的一点,但我认为答案在于documentation for shutdown
的措辞:
发起在以前已提交任务的执行一个有序的关闭,但没有新的任务将被接受。
您的第一个任务符合“先前提交的任务”的要求,因此shutdown()会等待它执行。
从技术上讲,重复的任务是以前提交的,但是因为它会一直重复,所以等待它完成是不可能的。试图这样做会违反shutdown()的合同。所以,我想说唯一的选择是忽略重复任务的未来执行。