简体   繁体   English

在所有提交的任务完成后关闭 Java Executor 没有阻塞

[英]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.

相关问题 在不知道何时完成所有任务的情况下关闭执行程序 - Shutdown executor without knowing when it will finish all the tasks 如何等待直到ExecutorService中的所有提交任务都完成而没有关闭? - How to wait until all submitted tasks in ExecutorService are completed without shutdown? 什么是最好的方式来知道执行器服务何时完成所有提交的任务 - what is the best way to know when all submitted tasks has been finished by Executor Service Java中没有executorService的关机执行程序 - Shutdown executor without executorService in Java Java 8并发 - 等待任务关闭执行程序 - Java 8 concurrency - Wait for tasks to shutdown executor java并发包中是否有任何执行程序可以确保所有任务按提交顺序完成? - Are there any executor in java concurrent package which guarantee that all tasks will be done in order they were submitted? 如何在不丢失任务的情况下关闭和重新实例化 Executor Service - How to shutdown and reinstantiate an Executor Service without loosing tasks 所有任务完成后,执行器服务如何发出信号? - how can executor service signal when all tasks are finished? Java 执行器服务:等待所有任务完成 - Java executor service: Waiting for all tasks to finish shutdown executor service java - shutdown executor service java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM