在我的程序中CountDownLatch的await()方法会继续阻塞程序,CountDownLatch正如它所写,是一个倒计时锁存器,当count到0时触发三个Thread执行,并证明当cdAnswer减为0时三个Thread已经被执行,那么主线程执行,但在我的程序中,三个线程只完成了两个主线程,谁可以帮助我,我将非常感激。底部是我的程序。
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();
}
}
问题补充:这个结果不是我所期望的,我以为这句话'已经收到了所有的回应。此任务的结果已经完成'将在最终打印中