首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Java 多線程協作:使用 CountDownLatch 讓主線程等待子線程完成

     編輯:Java 綜合教學

CountDownLatch 原理

基於 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 實現雙向同步(所有線程互相等待)。
  • Java 7+ Phaser 支持動態註冊/取消參與者,功能更強。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved