運行每個線程時爲什麼即使在前一個線程已經調用countdown.countDown()並將Latch Count減少1之後,爲什麼countdown.getCount()始終會打印'3'?Java - COUNTDOWNLATCH中的計數
我有點厭倦了Java如何知道Latch Count已經達到0,以便它可以釋放所有3個線程。
import java.util.concurrent.CountDownLatch;
class b {
static final CountDownLatch countdown = new CountDownLatch(3);
public static void main(String[] args) {
for (int i = 0; i < 3; ++i) {
Thread t = new Thread() {
public void run() {
System.out.printf("Starting on %d other threads.\n",
countdown.getCount());
countdown.countDown();
System.out.printf("new on %d other threads.\n",
countdown.getCount());
try {
countdown.await(); // waits until everyone reaches this
// point
// System.out.println("Go again : "
// +countdown.getCount());
} catch (Exception e) {
}
}
};
t.start();
}
System.out.println("Go");
}
}
上一個線程已經調用countdown.countDown()之後,邏輯錯誤出現在*中*:它可能沒有 – assylias
http://ideone.com/EloGi9 - 在那裏工作正常。如果你幸運,它的行爲就像你期望的那樣。這就是未定義的多線程行爲的美妙之處 – zapl