固定线程池立即退出,不处理线程 [英] Fixed Thread Pool is exiting immediately, not processing threads
问题描述
试图了解固定线程池,我编写了此测试代码,该代码显示了以下结果,与我认为的结果相反:
Trying to understand fixed thread pools I made this test code, which revealed the below results, contrary to what I thought it would do:
Thread Start: 1
Thread Start: 2
Thread Start: 0
就是这样.没有线程结束"消息,仅启动了3个线程.
That's it. No "Thread End" messages and only 3 threads were started.
我希望而且我希望所有10个任务都可以完成.
I expected and I want all 10 tasks to complete.
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.shutdown();
之后调用exec.awaitTermination(1, TimeUnit.HOUR);
(当然,超时对于您的应用程序来说很有意义).
exec.shutdown()
doesn't block main thread. If you need to wait for all submitted tasks to finish you need to call exec.awaitTermination(1, TimeUnit.HOUR);
(of course with timeout that makes sense for your application) after call to 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;
这篇关于固定线程池立即退出,不处理线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!