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

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

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

CountDownLatch 的基本原理

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

CountDownLatch 的用法

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

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

CountDownLatch 示例

下面通過一個簡單的示例代碼來演示 CountDownLatch 的用法。假設(shè)有一個需求,需要三個工人協(xié)同完成一項任務(wù),主線程需要等待三個工人完成任務(wù)后才能繼續(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(); // 主線程等待三個工人線程完成任務(wù)
            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(); // 工人完成任務(wù)后調(diào)用 countDown()
        }
    }
}

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

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

擴展:上面的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(); // 主線程等待三個工人線程完成任務(wù)
        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 用于等待多個線程完成任務(wù)后再繼續(xù)執(zhí)行,而 join 用于等待一個線程執(zhí)行完畢后再繼續(xù)執(zhí)行。另外,CountDownLatch 是基于計數(shù)器的實現(xiàn),可以靈活地控制線程的數(shù)量和完成順序;而 join 方法只能等待單個線程執(zhí)行完畢。

總結(jié)

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

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

相關(guān)文章

最新評論

阿克| 呈贡县| 土默特右旗| 甘泉县| 松桃| 体育| 沙雅县| 博客| 承德市| 霍州市| 德钦县| 遵义市| 内乡县| 塔城市| 剑阁县| 卫辉市| 壶关县| 张家界市| 望谟县| 怀集县| 如东县| 科技| 大庆市| 新竹县| 慈利县| 巨鹿县| 洞口县| 安新县| 本溪市| 泸州市| 迁安市| 南平市| 牙克石市| 河北区| 凤山市| 海原县| 射阳县| 石门县| 安义县| 信宜市| 铜陵市|