Java shutdown 和 awaitTermination 哪个第一次调用有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18425026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:31:56  来源:igfitidea点击:

shutdown and awaitTermination which first call have any difference?

javamultithreadingexecutorservice

提问by Amitābha

What is the difference between

之间有什么区别

ExecutorService eService = Executors.newFixedThreadPool(2);
eService.execute(new TestThread6());
eService.execute(new TestThread6());
eService.execute(new TestThread6());
eService.awaitTermination(1, TimeUnit.NANOSECONDS);
eService.shutdown();

and

eService.shutdown();
eService.awaitTermination(1, TimeUnit.NANOSECONDS);

I don't really understand shutdown(). This method does not wait for previously submitted tasks to complete execution. Does it mean shutdown()may terminate the tasks which have been submitted, but not completed? I tried some examples, they do not prove it, please give me an example.

我真的不明白shutdown()。此方法不等待先前提交的任务完成执行。是否意味着shutdown()可以终止已提交但未完成的任务?我尝试了一些例子,他们不能证明这一点,请给我一个例子。

采纳答案by Chris Jester-Young

You should call shutdownfirst. Otherwise, you might be waiting for a very long time, since awaitTerminationdoesn't actually shut down your executor.

你应该shutdown先打电话。否则,您可能会等待很长时间,因为awaitTermination实际上并没有关闭您的执行程序。

If you wanted to wait for tasks to complete, rather than wait for the executor to shut down, then you should use invokeAll.

如果你想等待任务完成,而不是等待执行器关闭,那么你应该使用invokeAll.

回答by Evgeniy Dorofeev

After we start the first task ThreadPoolExecutor will start a Thread that will not end even after the task is finished. At least it's true for a fixed thread pool. This is why we need to call shutdown. After shutdown ThreadPoolExecutor will reject any new task but will wait for running tasks to finish and then allow the Threads to end. This is why we need awaitTermination after shutdwon.

在我们启动第一个任务后,ThreadPoolExecutor 将启动一个即使在任务完成后也不会结束的线程。至少对于固定线程池来说是这样。这就是为什么我们需要调用shutdown。关闭后 ThreadPoolExecutor 将拒绝任何新任务,但会等待正在运行的任务完成,然后允许线程结束。这就是为什么我们在shutdwon 之后需要awaitTermination。

回答by Terry Li

shutdownmeans the executor service takes no more incoming tasks.

关闭意味着执行程序服务不再接受传入的任务。

awaitTerminationis invoked after a shutdown request.

awaitTermination在关闭请求后被调用。

You need to first shut down the service and then block and wait for threads to finish.

您需要先关闭服务,然后阻塞并等待线程完成。

If you want to see all threads finish running and insist on using awaiTermination, you need to set the timeout parameter to be big enough. So you could do:

如果你想看到所有线程都跑完并坚持使用awaiTermination,则需要将 timeout 参数设置得足够大。所以你可以这样做:

eService.shutdown();
if (!eService.awaitTermination(60000, TimeUnit.SECONDS))
    System.err.println("Threads didn't finish in 60000 seconds!");
}

Alternatively, you could do:

或者,你可以这样做:

eService.shutdown();
while (!eService.isTerminated()) {

}

This way you are able to ensure all threads are finished running unless they are interrupted unexpectedly.

这样您就可以确保所有线程都完成运行,除非它们被意外中断。

回答by S.D.

Reading the documentation always helps:

阅读文档总是有帮助的:

shutdownNow:

立即关机

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution. These tasks are drained (removed) from the task queue upon return from this method.

This method does not wait for actively executing tasks to terminate.Use awaitTermination to do that.

There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. This implementation cancels tasks via Thread.interrupt(), so any task that fails to respond to interrupts may never terminate

尝试停止所有正在执行的任务,停止等待任务的处理,并返回等待执行的任务列表。从该方法返回时,这些任务将从任务队列中排出(移除)。

此方法不会等待主动执行的任务终止。使用 awaitTermination 来做到这一点。

除了尽力尝试停止处理正在执行的任务之外,没有任何保证。此实现通过 Thread.interrupt() 取消任务,因此任何未能响应中断的任务可能永远不会终止

shutdown:

关机

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.Invocation has no additional effect if already shut down.

This method does not wait for previously submitted tasks to complete execution. Use awaitTerminationto do that.

启动有序关闭,其中执行先前提交的任务,但不会接受新任务。如果已经关闭,调用没有额外的效果。

此方法不等待先前提交的任务完成执行。使用awaitTermination这样做。

awaitTermination:

等待终止

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

阻塞直到所有任务在关闭请求后完成执行,或者超时发生,或者当前线程被中断,以先发生者为准。

回答by user3094331

You need to call shutdownNow()method after the awaitTermination()method call happened. Then only you can find out the actual usage of awaitTermination()method.

您需要shutdownNow()awaitTermination()方法调用发生后调用方法。那么只有你才能找出awaitTermination()方法的实际用法。

回答by user11656780

executorService.execute(runnableTask);  

//executorService.shutdown(); //it will make the executorService stop accepting new tasks
//executorService.shutdownNow(); //tires to destroy the executorService immediately, but it doesn't guarantee that all the running threads will be destroyed at the same time. This method returns list of tasks which are waiting to be processed.
//List<Runnable> notExecutedTasks = executorService.shutdownNow(); //this method returns list of tasks which are waiting to be processed.developer decide what to do with theses tasks?

//one good way to shutdown the executorService is use both of these methods combined with the awaitTermination
executorService.shutdown();
try{
    if(!executorService.awaitTermination(1000, TimeUnit.MICROSECONDS)) {
        executorService.shutdownNow();
    }
}catch (InterruptedException e){
    e.printStackTrace();
}

回答by Ashwani Tiwari

Main Difference

主要区别

shutdown()-

关机()-

1. Not block the calling a thread - means a thread who called the shutdown().
2. Excecutor not accepting new task after calling shutdown().

awaitTermination-

等待终止-

1. Block the calling thread. (as join() method do)

Confusion Point- because shutdown() not killing the previously submitted task , then why awaitTermination()

混淆点- 因为 shutdown() 没有杀死之前提交的任务,那为什么 awaitTermination()

shutdown() also not kill any task which is previously submitted means submitted tasks and currently running tasks are allowed to continue , then why need awaitTermination().

shutdown() 也不会杀死任何先前提交的任务意味着允许提交的任务和当前正在运行的任务继续,那么为什么需要 awaitTermination()。

Suppose you can wait for 10 min onlyto complete all the task that are submitted and after that want to call shutdownNow()(---you already know what it do) then use awaitTermination() after calling shutdown().

假设你只能等待10 分钟来完成所有提交的任务,然后想调用 shutdownNow()(---你已经知道它做了什么) 然后在调用 shutdown() 后使用 awaitTermination()。

And if there is no time restriction , then shutdown() is ok. No need of awaitTermination().

如果没有时间限制,那么 shutdown() 就可以了。不需要 awaitTermination()。

回答by Gawain

From Java8 ThreadPool awaitTermination method:

来自 Java8 ThreadPool awaitTermination 方法:

    try {
        for (;;) {
            if (runStateAtLeast(ctl.get(), TERMINATED))
                return true;
            if (nanos <= 0)
                return false;
            nanos = termination.awaitNanos(nanos);
        }
    } finally {
        mainLock.unlock();
    }

It will first check run state of thread pool. And if the thread pool is not shut down(which set run state to terminated), awaitTermination method will not return until timeout. This explains why await a long time if you await first then shutdown.

它将首先检查线程池的运行状态。如果线程池没有关闭(将运行状态设置为终止), awaitTermination 方法将不会返回,直到超时。这解释了为什么如果您先等待然后关闭,则等待很长时间。

回答by Xavy Guzman

the best implementation:

最佳实现:

executor.shutdown();
    try {
         if (!executor.awaitTermination(3500, TimeUnit.MILLISECONDS)) {
            executor.shutdownNow();
         }                  
    } catch (InterruptedException e) {              
        executor.shutdownNow();
    }