java - 固定线程池立即退出,不处理线程
问题描述
为了理解固定线程池,我编写了这个测试代码,它显示了以下结果,与我认为的相反:
Thread Start: 1
Thread Start: 2
Thread Start: 0
而已。没有“线程结束”消息,只启动了 3 个线程。
我期望并且我希望完成所有 10 项任务。
ExecutorService exec = Executors.newFixedThreadPool(3);
for (int c = 0; c < 10; c++) {
exec.execute(new TestThread(c));
}
exec.shutdown();
public class TestThread implements Runnable {
private int counter;
public TestThread (int counter) {
this.counter = counter;
}
@Override
public void run() {
System.out.println("Thread Start: " + counter);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread End: " + counter);
}
}
解决方案
exec.shutdown()
不会阻塞主线程。如果您需要等待所有提交的任务完成,您需要exec.awaitTermination(1, TimeUnit.HOUR);
在调用exec.shutdown();
.
/**
* Blocks until all tasks have completed execution after a shutdown
* request, or the timeout occurs, or the current thread is
* interrupted, whichever happens first.
*/
boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException;
推荐阅读
- angular-cli - 如何从观察者文件中排除 node_modules
- plotly-dash - 为什么 plotly 的配置在 dash 中不起作用?
- wordpress - Wordpress 根文件夹内的错误 404 MyBB 文件夹
- docker - Docker-Compose:更新后无法访问服务
- python - 我在哪里可以找到在自然图像上训练的预训练变分自动编码器?
- python - 使用Pyhton for循环,我怎样才能每次都从字符串中取出一个字母而不重复
- azure-active-directory - 使用 azuread-openidconnect 的 express js 的 Passport 中间件
- python - python - 如何使用复杂的构造函数从python中的jsons创建对象?
- git - .gitignore 模式递归地忽略所有文件,但不是文件夹,也不是其他 .gitignore 文件
- angular7 - 如何使用angular7显示谷歌弹出确认对话框?