繁体   English   中英

Executor Service的shutdown和shutdownNow的区别

[英]Difference between shutdown and shutdownNow of Executor Service

我想知道关闭Executor Serviceshutdown()shutdownNow()之间的基本区别?

据我了解:

shutdown()应用于正常关闭,这意味着所有正在运行并排队等待处理但未启动的任务都应该被允许完成

shutdownNow()突然关闭意味着一些未完成的任务被取消,未开始的任务也被取消。 还有什么我遗漏的隐式/显式的吗?

PS:我发现了另一个关于如何关闭与此相关但不完全是我想知道的执行程序服务的问题。

总结一下,你可以这样想:

  • shutdown()只会告诉执行服务它不能接受新的任务,但是已经提交的任务继续运行
  • shutdownNow()会做同样的事情,并且会尝试通过中断相关线程来取消已经提交的任务。 请注意,如果您的任务忽略中断,则shutdownNow的行为将与shutdown完全相同。

您可以尝试下面的示例并将shutdown替换为shutdownNow以更好地理解不同的执行路径:

  • 使用shutdown时,输出为Still waiting after 100ms: calling System.exit(0)...因为正在运行的任务没有被中断并继续运行。
  • 使用shutdownNow ,输出被interruptedExiting normally...因为正在运行的任务被中断,捕获中断然后停止它正在做的事情(打破 while 循环)。
  • 使用shutdownNow ,如果您注释掉 while 循环中的行,您将得到Still waiting after 100ms: calling System.exit(0)...因为正在运行的任务不再处理中断。
public static void main(String[] args) throws InterruptedException {
    ExecutorService executor = Executors.newFixedThreadPool(1);
    executor.submit(new Runnable() {

        @Override
        public void run() {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println("interrupted");
                    break;
                }
            }
        }
    });

    executor.shutdown();
    if (!executor.awaitTermination(100, TimeUnit.MICROSECONDS)) {
        System.out.println("Still waiting after 100ms: calling System.exit(0)...");
        System.exit(0);
    }
    System.out.println("Exiting normally...");
}
  • shutdown()

要终止 ExecutorService 中的线程,您可以调用它的shutdown()方法。 ExecutorService 不会立即关闭,但它不会再接受新的任务,一旦所有线程都完成当前任务,ExecutorService 就会关闭。 在调用 shutdown() 之前提交给 ExecutorService 的所有任务都会执行。

  • shutdownNow()

如果想立即关闭ExecutorService,可以调用shutdownNow()方法。 这将尝试立即停止所有正在执行的任务,并跳过所有已提交但未处理的任务。 没有关于执行任务的保证。 也许他们停下来,也许执行到最后。 这是尽力而为的尝试。

javadocs

void shutdown

启动有序关闭,其中执行先前提交的任务,但不会接受新任务。

List<Runnable> shutdownNow()

尝试停止所有正在执行的任务,停止等待任务的处理,并返回等待执行的任务列表。

除了尽最大努力停止处理正在执行的任务之外,没有任何保证

例如,典型的实现将通过 Thread.interrupt() 取消,因此任何未能响应中断的任务可能永远不会终止。

返回:从未开始执行的任务列表

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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