我有这个简单的架构:
int parallelism = 4; //4 tasks
ExecutorService executor = Executors.newCachedThreadPool();
CountDownLatch latch = new CountDownLatch(parallelism);
for(int i=0;i<parallelism;i++){
executor.execute(new MyTask());
}
latch.await();
System.out.println("done");
任务只是调用
public void run(){
System.out.println("working");
latch.countDown();
}
即使执行给了我:
working
working
working
working
done
整个程序继续执行!怎么样?
答案 0 :(得分:3)
您需要关闭Executor
。
ExecutorService executor = Executors.newCachedThreadPool();
// ...
executor.shutdown();
while ( executor.awaitTermination(1, TimeUnit.SECONDS)) {
System.out.println("This is taking too long.");
}
即使所有的runnable都已完成,Executor
仍保留池中的线程。这些正在阻碍你的退出。在所有非守护程序线程完成之前,main
线程不会退出。
另请参阅Turning an ExecutorService to daemon in Java以获取另一种选择 - 使Executor
使用守护程序线程。