在我的程序CountDownLatch中,await()方法将继续阻塞程序,CountDownLatch在写入时, 是一个倒计时锁存器,当计数为零时触发三个线程执行,并证明当cdAnswer减少为0时三 线程已执行,然后执行主线程,但在我的程序中,只有三个线程完成 两个主线程进行了,谁能帮助我,我将非常感激。 底部是我的程序。
public class CountdownLatchTest {
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
final CountDownLatch cdOrder = new CountDownLatch(1);
final CountDownLatch cdAnswer = new CountDownLatch(3);
for (int i = 0; i < 3; i++) {
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
System.out.println("Thread" + Thread.currentThread().getName()
+ "Wait for the command");
cdOrder.await();
System.out.println("Thread" + Thread.currentThread().getName()
+ "received command");
Thread.sleep((long) (Math.random() * 10000));
System.out.println("Thread" + Thread.currentThread().getName()
+ "Feedback the results");
cdAnswer.countDown();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("To complete the order");
cdAnswer.countDown();
}
}
};
service.execute(runnable);
}
try {
Thread.sleep((long) (Math.random() * 10000));
System.out.println("Thread" + Thread.currentThread().getName()
+ "The upcoming orders");
cdOrder.countDown();
System.out.println("Thread" + Thread.currentThread().getName()
+ "Sent the command, are waiting for the result");
cdAnswer.await();
System.out.println("Thread" + Thread.currentThread().getName()
+ "Have received all the response. "
+ "The results of this task has been completed");
} catch (Exception e) {
e.printStackTrace();
}
service.shutdown();
}
}
问题补充: 这个结果不是我的预期,我以为这句话“收到了所有回复。这项任务的结果已经完成“将在最后的印刷品中
答案 0 :(得分:2)
这是因为如果你看到runnable的运行方法
public void run() {
try {
System.out.println("Thread"
+ Thread.currentThread().getName()
+ "Wait for the command");
cdOrder.await();
System.out.println("Thread"
+ Thread.currentThread().getName()
+ "received command");
Thread.sleep((long) (Math.random() * 10000));
System.out.println("Thread"
+ Thread.currentThread().getName()
+ "Feedback the results");
cdAnswer.countDown(); -- countdown on latch cdAnswer
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("To complete the order");
cdAnswer.countDown(); -- countdown on latch cdAnswer
}
}
cdAnswer.countDown();对于finally中的每个runnable和在catch子句之前的一个被调用两次。 因此,对于三个线程,倒计时被调用六次,因此主线程在3倒计时后开始。
删除cdAnswer.countDown();就在catch语句之上,它按预期工作