ThreadPoolExecutor 关闭 API 文档废话 "does not wait"

ThreadPoolExecutor shutdown API doc verbiage "does not wait"

ThreadPoolExector#shutdown 的文档中说:

This method does not wait for previously submitted tasks to complete execution

这是什么意思?

因为我认为这意味着已提交的排队任务可能无法完成,但事实并非如此;请参阅此示例代码,它在完成所有提交的任务之前调用关闭:

package example;

import java.util.concurrent.*;

public class ExecutorTest {

    public static void main(String ... args) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 10; i++) {
            final int count = i;
            executorService.execute(() -> {
                System.out.println("starting " + count);
                try {
                    Thread.sleep(10000L);
                } catch (InterruptedException e) {
                    System.out.println("interrupted " + count);
                }
                System.out.println("ended " + count);
            });
        }
        executorService.shutdown();         
    }    
}

打印:

C:\>java -cp . example.ExecutorTest
starting 0
starting 2
starting 1
ended 2
ended 0
starting 3
starting 4
ended 1
starting 5
ended 3
ended 5
ended 4
starting 7
starting 6
starting 8
ended 7
ended 6
ended 8
starting 9
ended 9

C:\>

在这个例子中,提交的任务完成执行似乎很清楚。我已经 运行 在 JDK8 上使用 Oracle 和 IBM JDK 进行了此操作并得到了相同的结果。

那么文档中的那一行试图说明什么?还是有人为 shutdownNow 写了这篇文章,然后无意中将其剪切并粘贴到关闭文档中?

shutdown() 的 javadoc 的完整引用:

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 awaitTermination to do that.

关闭执行器会阻止提交新任务

已经提交的任务,无论是已开始还是还在队列中等待,都会执行完毕。


如果您不想执行排队的任务,请调用 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.

是否停止已经启动的任务取决于任务,如上一段所述。

ThreadPoolExector#shutdown的文档中,多了一句:

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

在此上下文中,这意味着 调用者线程 不等待先前提交的任务完成执行。换句话说,shutdown() 不会阻塞调用者线程。


如果您确实需要阻止调用者线程,请使用 ThreadPoolExector#awaitTermination(long timeout, TimeUnit unit):

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