[英]Shutdown Java Executor After All Submitted Tasks Finished Without Blocking
I'm wondering if there is a way to shutdown a Java ExecutorService
and allow all submitted tasks to finish while not blocking.我想知道是否有办法关闭 Java ExecutorService
并允许所有提交的任务在不阻塞的情况下完成。
to be more specific, I want to schedule a Runnable
with a delay and continue with the code, without the need to keep a reference to the ExecutorService
to be able to shut it down.更具体地说,我想延迟一个Runnable
并继续执行代码,而不需要保留对ExecutorService
的引用来关闭它。
The following code will terminate the submitted task as it hasn't started yet:以下代码将终止尚未启动的提交任务:
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.schedule(runnable, delay, TimeUnit.MILLISECONDS);
executor.shutdown();
...
While this code will block until the task is finished:虽然此代码将阻塞,直到任务完成:
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.schedule(runnable, delay, TimeUnit.MILLISECONDS);
executor.awaitTermination(timeout, TimeUnit.MILLISECONDS);
...
I want to have something like this:我想要这样的东西:
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.schedule(runnable, delay, TimeUnit.MILLISECONDS);
executor.shutdownAfterTerminationWithoutBlocking();
...
code that runs without waiting
I know this possible using Timer
but i'm wondering if this is possible using ExecutorService
我知道这可以使用Timer
但我想知道这是否可以使用ExecutorService
ExecutorService.shutdown
javadoc says: ExecutorService.shutdown
javadoc 说:
Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.启动有序关闭,其中执行先前提交的任务,但不会接受新任务。
So tasks that already submitted, but not yet started, will be executed.因此,已提交但尚未启动的任务将被执行。 Exactly as you need.完全按照您的需要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.