试图了解固定线程池,我编写了此测试代码,该代码揭示了以下结果,与我认为的结果相反:
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);
}
}
答案 0 :(得分:1)
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;