为什么程序等待 schedule() 完成但不等待 scheduleWithFixedDelay()?

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() 但之后它在没有 运行ning scheduleWithFixedDelay() 的情况下完成。

我怀疑原因是 schedule() 与 scheduleWithFixedDelay() 不同,它是同步执行的,但我没有在文档中找到支持这一点的论据。

这有点微妙,但我认为答案就在于documentation for shutdown的措辞:

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

您的第一个任务符合“先前提交的任务”的条件,因此 shutdown() 等待它执行。

从技术上讲,重复任务之前已提交,但由于它会永远重复,等待它完成是不可能的。尝试这样做会违反 shutdown() 的约定。所以,我想说唯一的选择是忽略未来重复任务的执行。