我想了解countDownLatch,我有这个程序,但我不知道为什么我的程序没有返回而没有完成。
package countDownLatches;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class Processor implements Runnable {
CountDownLatch latch;
public Processor(CountDownLatch latch) {
this.latch = latch;
}
public void run() {
System.out.println("thread started: ");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
}
}
public class App {
public static void main(String args[]) {
CountDownLatch latch = new CountDownLatch(3);
ExecutorService executorService = Executors.newFixedThreadPool(3);
for (int i = 0; i < 3; i++) {
executorService.submit(new Processor(latch));
}
try {
latch.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("task completed");
}
}
答案 0 :(得分:3)
您需要关闭执行程序服务。在for
循环后添加此行:
executorService.shutdown();
等待所有正在执行的任务终止的替代方法是
executorService.awaitTermination();
您可以在ExecutorService Javadoc中阅读更多内容。
答案 1 :(得分:1)
您需要shutdown your executor service properly。或者它将无限期地等待新任务。
添加:
executorService.shutdown();
在:
System.out.println("task completed");
我认为,主要的原因,为什么它在java api中完成,是因为executorService可能从多个线程(除了main)接收任务,所以 - 为什么它应该停止,当没有更多的动作时主线程?是的,我相信,它不应该。