基於 AQS 共享鎖,計數器初始化為 N,每次 countDown() 遞減,await() 阻塞直到計數歸零。適用於「一組線程並行執行,主線程匯總結果」場景。
import java.util.concurrent.CountDownLatch;
public class ThreadWaitDemo {
public static void main(String[] args) throws InterruptedException {
int threadCount = 10;
CountDownLatch latch = new CountDownLatch(threadCount);
for (int i = 0; i < threadCount; i++) {
final int id = i;
new Thread(() -> {
try {
Thread.sleep(1000); // 模擬業務耗時
} catch (InterruptedException ignored) {}
System.out.printf("Thread-%d finished%n", id);
latch.countDown();
}).start();
}
latch.await(); // 主線程阻塞在此
System.out.println("All child threads done, main continues.");
}
}
await(timeout, TimeUnit):超時返回 false,避免無限等待。CyclicBarrier 實現雙向同步(所有線程互相等待)。Phaser 支持動態註冊/取消參與者,功能更強。