在ThreadPoolExector#shutdown的文档中,它说:
This method does not wait for previously submitted tasks to complete execution
那是什么意思?
因为我认为已经提交的排队任务可能无法完成,但事实并非如此;请参阅此示例代码,该代码在完成所有提交的任务之前调用shutdown:
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:\>
在这个例子中,很明显提交的任务完成了执行.我使用Oracle和IBM JDK在JDK8上运行它并获得相同的结果.
那么文档试图说的是什么?或者是否有人为shutdownNow写了这个并将其剪切并粘贴到文档中以便无意中关闭?
解决方法:
在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.