简体   繁体   中英

Why does the program wait for the schedule() to finish but doesn't wait for the scheduleWithFixedDelay()?

Here's the code:

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();
    }
}

When executing the above code the program waits 5 seconds to run schedule() but after that it finishes without running the scheduleWithFixedDelay().

I suspect the reason is that schedule() is executed synchronously unlike the scheduleWithFixedDelay() but I haven't found the arguments in favor of this in the docs.

This is a bit subtle, but I think the answer lies in the wording of the documentation for shutdown :

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

Your first task qualifies as a “previously submitted task,” so shutdown() waits for it to execute.

Technically, the repeating task was previously submitted, but since it repeats forever, waiting for it complete is impossible. Attempting to do so would violate the contract of shutdown(). So, I would say that the only alternative is to ignore future executions of repeating tasks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM