最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JAVA 多線程編程之CountDownLatch使用詳解

 更新時間:2023年05月21日 16:35:30   作者:jcuser  
當多個線程需要協(xié)調(diào)和同步執(zhí)行任務時,Java中的CountDownLatch(倒計時門閂)是一個常用的工具類,本文將介紹 CountDownLatch 的基本原理、用法以及示例代碼,需要的朋友可以參考下

CountDownLatch 的基本原理

CountDownLatch 是基于計數(shù)器的原理實現(xiàn)的,它內(nèi)部維護了一個整型的計數(shù)器。創(chuàng)建一個 CountDownLatch 對象時,需要指定一個初始計數(shù)值,該計數(shù)值表示需要等待的線程數(shù)量。每當一個線程完成了其任務,它調(diào)用 CountDownLatch 的 countDown() 方法,計數(shù)器的值就會減一。當計數(shù)器的值變成 0 時,等待的線程就會被喚醒,繼續(xù)執(zhí)行它們的任務。

CountDownLatch 的用法

CountDownLatch 在多線程編程中有廣泛的應用場景,例如主線程等待所有子線程完成任務后再繼續(xù)執(zhí)行,多個線程協(xié)同完成一個任務等。以下是 CountDownLatch 的基本用法:

  • 創(chuàng)建 CountDownLatch 對象,并指定初始計數(shù)值。
CountDownLatch latch = new CountDownLatch(3); // 初始計數(shù)值為 3
  • 創(chuàng)建需要等待的線程,線程完成任務后調(diào)用 countDown() 方法。
Runnable task = new Runnable() {
    @Override
    public void run() {
        // 線程任務邏輯
        // ...
        latch.countDown(); // 完成任務后調(diào)用 countDown()
    }
};
  • 創(chuàng)建等待線程,等待計數(shù)器的值變成 0 后再繼續(xù)執(zhí)行。
try {
    latch.await(); // 等待計數(shù)器的值變成 0
    // 繼續(xù)執(zhí)行需要等待的線程后續(xù)邏輯
} catch (InterruptedException e) {
    // 處理中斷異常
    e.printStackTrace();
}

CountDownLatch 示例

下面通過一個簡單的示例代碼來演示 CountDownLatch 的用法。假設有一個需求,需要三個工人協(xié)同完成一項任務,主線程需要等待三個工人完成任務后才能繼續(xù)執(zhí)行。示例代碼如下:

import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample {
    public static void main(String[] args) {
        final int workerCount = 3;
        final CountDownLatch latch = new CountDownLatch(workerCount);

        // 創(chuàng)建并啟動三個工人線程
        for (int i = 0; i < workerCount; i++) {
            Worker worker = new Worker(latch, "Worker " + (i + 1));
            new Thread(worker).start();
        }

        try {
            System.out.println("Main thread is waiting for workers to finish...");
            latch.await(); // 主線程等待三個工人線程完成任務
            System.out.println("All workers have finished, main thread continues...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    static class Worker implements Runnable {
        private final CountDownLatch latch;
        private final String name;

        public Worker(CountDownLatch latch, String name) {
            this.latch = latch;
            this.name = name;
        }

        @Override
        public void run() {
            System.out.println(name + " starts working...");
            // 模擬工作耗時
            try {
                Thread.sleep((long) (Math.random() * 10000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(name + " finishes working.");
            latch.countDown(); // 工人完成任務后調(diào)用 countDown()
        }
    }
}

在上述代碼中,首先創(chuàng)建了一個 CountDownLatch 對象,并指定初始計數(shù)值為 3。然后創(chuàng)建了三個工人線程并啟動,每個工人線程模擬完成一項工作后調(diào)用 countDown() 方法,計數(shù)器的值減一。最后,主線程調(diào)用 await() 方法等待計數(shù)器的值變成 0,表示所有工人都完成任務后再繼續(xù)執(zhí)行。

運行該程序后,輸出結(jié)果如下:

Worker 1 starts working...  
Worker 2 starts working...  
Worker 3 starts working...  
Main thread is waiting for workers to finish...  
Worker 2 finishes working.  
Worker 1 finishes working.  
Worker 3 finishes working.  
All workers have finished, main thread continues...

可以看到,主線程在三個工人線程完成任務后才繼續(xù)執(zhí)行,并且所有工人線程的完成順序是不確定的,但主線程會一直等待直到所有工人完成任務。

擴展:上面的worker線程運行是沒有順序的,我們可以使用join()來使線程有序等待上一個線程運行結(jié)束。

public static void main(String[] args) throws InterruptedException {
    final int workerCount = 3;
    final CountDownLatch latch = new CountDownLatch(workerCount);
    System.out.println("Main thread is waiting for workers to finish...");
    // 創(chuàng)建并啟動三個工人線程
    for (int i = 0; i < workerCount; i++) {
        Worker worker = new Worker(latch, "Worker " + (i + 1));
        Thread t = new Thread(worker);
        t.start();
        t.join(); // 等待上一個線程執(zhí)行完成
    }
    try {
        latch.await(); // 主線程等待三個工人線程完成任務
        System.out.println("All workers have finished, main thread continues...");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

輸出結(jié)果:

Main thread is waiting for workers to finish...
Worker 1 starts working...
Worker 1 finishes working.
Worker 2 starts working...
Worker 2 finishes working.
Worker 3 starts working...
Worker 3 finishes working.
All workers have finished, main thread continues...

CountDownLatch 和 join 的作用和使用方式不同。CountDownLatch 用于等待多個線程完成任務后再繼續(xù)執(zhí)行,而 join 用于等待一個線程執(zhí)行完畢后再繼續(xù)執(zhí)行。另外,CountDownLatch 是基于計數(shù)器的實現(xiàn),可以靈活地控制線程的數(shù)量和完成順序;而 join 方法只能等待單個線程執(zhí)行完畢。

總結(jié)

CountDownLatch 是一個非常實用的線程同步工具,在多線程編程中有著廣泛的應用。它基于計數(shù)器的原理實現(xiàn),通過等待計數(shù)器的值變成 0 來實現(xiàn)線程的同步和協(xié)作。在使用 CountDownLatch 時,需要注意初始計數(shù)值的設定和 countDown() 和 await() 方法的使用。 本文介紹了 CountDownLatch 的基本原理和用法,并通過示代碼演示了它的使用。希望本文能夠幫助讀者更好地理解和應用 CountDownLatch,在實際的項目中提高多線程編程的效率和質(zhì)量。

以上就是JAVA 多線程編程之CountDownLatch使用詳解的詳細內(nèi)容,更多關于JAVA CountDownLatch的資料請關注腳本之家其它相關文章!

相關文章

最新評論

梅州市| 紫金县| 赤峰市| 平湖市| 林口县| 前郭尔| 车险| 恭城| 瑞安市| 古丈县| 常熟市| 昭通市| 新余市| 徐闻县| 宁强县| 武胜县| 犍为县| 汕头市| 农安县| 河曲县| 收藏| 大安市| 沙田区| 祥云县| 长春市| 肃南| 肥乡县| 云南省| 股票| 正蓝旗| 四子王旗| 南澳县| 恩平市| 新竹县| 阜平县| 称多县| 鄢陵县| 襄城县| 南通市| 确山县| 阿城市|