[英]Why does the program wait for the schedule() to finish but doesn't wait for the 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秒鍾以運行schedule(),但此后它會結束而不運行scheduleWithFixedDelay()。
我懷疑原因是schedule()是同步執行的,與scheduleWithFixedDelay()不同,但是我在文檔中沒有找到支持此的參數。
這有點微妙,但我認為答案就在於shutdown
文檔的措辭:
啟動有序關閉,在該關閉中執行先前提交的任務,但不接受任何新任務。
您的第一個任務符合“先前提交的任務”的資格,因此shutdown()等待其執行。
從技術上講,重復任務是以前提交的,但是由於它會永遠重復,因此等待完成是不可能的。 嘗試這樣做會違反shutdown()的約定。 因此,我要說,唯一的選擇是忽略重復任務的未來執行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.