在我的程序中CountDownLatch的await()方法會繼續阻塞程序,CountDownLatch就像它寫的那樣, 是倒數鎖存器,當count爲零時觸發三個Thread執行,並且證明三個時cdAnswer降爲0 線程已經執行,然後主線程執行,但在我的程序中,三個線程只完成了 這兩個主線程被執行了,誰可以幫助我,我會非常感激。 底部是我的程序。關於CountDownLatch await()方法的問題?
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();
}
}
問題補充: 這個結果不出我所料,我想這句話「已收到所有的響應。該任務的結果已完成'將在最後打印
你能刪除中文字母嗎? –
我無法理解你到底有什麼問題。你能否詳細說明一下? –
非常好,這個問題的標題中的問號。 – Tunaki