问题
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
That's it. No "Thread End" messages and only 3 threads were started.
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);
}
}
回答1:
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;
来源:https://stackoverflow.com/questions/52632916/fixed-thread-pool-is-exiting-immediately-not-processing-threads