在所有提交的任务无阻塞地完成后关闭 Java 执行器

Shutdown Java Executor After All Submitted Tasks Finished Without Blocking

我想知道是否有办法关闭 Java ExecutorService 并允许所有提交的任务在不阻塞的情况下完成。

更具体地说,我想安排一个 Runnable 延迟并继续代码,而不需要保留对 ExecutorService 的引用才能将其关闭.

以下代码将终止提交的任务,因为它尚未开始:

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.schedule(runnable, delay, TimeUnit.MILLISECONDS);
executor.shutdown();
...

虽然此代码将阻塞直到任务完成:

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.schedule(runnable, delay, TimeUnit.MILLISECONDS);
executor.awaitTermination(timeout, TimeUnit.MILLISECONDS);
...

我想要这样的东西:

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.schedule(runnable, delay, TimeUnit.MILLISECONDS);
executor.shutdownAfterTerminationWithoutBlocking();
...
code that runs without waiting

我知道可以使用 Timer 但我想知道是否可以使用 ExecutorService

ExecutorService.shutdown javadoc 说:

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

因此将执行已提交但尚未开始的任务。正是您所需要的。