java – ThreadPoolExecutor关闭API doc verbiage“不等待”
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – ThreadPoolExecutor关闭API doc verbiage“不等待”,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1700字,纯文字阅读大概需要3分钟。
内容图文
![java – ThreadPoolExecutor关闭API doc verbiage“不等待”](/upload/InfoBanner/zyjiaocheng/797/a48ff9bc4fe347fe8da529051ef8ff2a.jpg)
在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.
内容总结
以上是互联网集市为您收集整理的java – ThreadPoolExecutor关闭API doc verbiage“不等待”全部内容,希望文章能够帮你解决java – ThreadPoolExecutor关闭API doc verbiage“不等待”所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。