溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Java?CountDownLatch計數(shù)器與CyclicBarrier循環(huán)屏障怎么定義

發(fā)布時間:2023-05-06 11:16:47 來源:億速云 閱讀:102 作者:iii 欄目:開發(fā)技術(shù)

本文小編為大家詳細介紹“Java CountDownLatch計數(shù)器與CyclicBarrier循環(huán)屏障怎么定義”,內(nèi)容詳細,步驟清晰,細節(jié)處理妥當,希望這篇“Java CountDownLatch計數(shù)器與CyclicBarrier循環(huán)屏障怎么定義”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識吧。

定義

CountDownLatch: A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

CyclicBarrier: A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.

上述是Oracle官方定義。簡單來說

CountDownLatch:計數(shù)器,允許一個或多個線程等待,直到在其他線程中執(zhí)行的一組操作完成。

CyclicBarrier:循環(huán)屏障,它允許一組線程相互等待以達到一個共同的屏障點。

區(qū)別

  • CountDownLatch 是 AQS (AbstractQueuedSynchronizer) 的一員,但 CyclicBarrier 不是。

  • CountDownLatch 的使用場景中,有兩類線程,一類是調(diào)用await()方法的等待線程,另一類是調(diào)用countDownl() 方法的操作線程。CyclicBarrier 的場景中,只有一類線程,都是相互等待的等待線程。

  • CountDownLatch 是減計數(shù),遞減完后不能復(fù)位,CyclicBarrier 是加計數(shù),遞增完后自動復(fù)位

CountDownLatch 示例

創(chuàng)建兩組線程,一組等待另一組執(zhí)行完才繼續(xù)進行

CountDownLatch countDownLatch = new CountDownLatch(5);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {
    executorService.execute(() -> {
        countDownLatch.countDown();
        System.out.println("run..");
    });
}
for (int i = 0; i < 3; i++) {  //我們要等上面執(zhí)行完成才繼續(xù)
    executorService.execute(() -> {
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("await..");
    });
}
executorService.shutdown();

打?。?/p>

run..
run..
run..
run..
run..
await..
await..
await..

等待累加線程執(zhí)行完,主線程再輸出累加結(jié)果

public class ThreadUnsafeExample {
    private int cnt = 0;
    public void add() {
        cnt++;
    }
    public int get() {
        return cnt;
    }
    public static void main(String[] args) throws InterruptedException {
        final int threadSize = 1000;
        ThreadUnsafeExample example = new ThreadUnsafeExample();
        final CountDownLatch countDownLatch = new CountDownLatch(threadSize);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < threadSize; i++) {
            executorService.execute(() -> {
                example.add();
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        System.out.println(example.get());
    }
}

打?。?/p>

997

3 模擬并發(fā)

ExecutorService executorService = Executors.newCachedThreadPool();
        CountDownLatch countDownLatch = new CountDownLatch(1);
        for (int i = 0; i < 5; i++) {
            executorService.submit( () -> {
                try {
                    countDownLatch.await();
                    System.out.println("【" + Thread.currentThread().getName() + "】開始執(zhí)行……");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        Thread.sleep(2000);
        countDownLatch.countDown();//開始并發(fā)
        executorService.shutdown();

打?。?/p>

【pool-2-thread-2】開始執(zhí)行&hellip;&hellip;
【pool-2-thread-5】開始執(zhí)行&hellip;&hellip;
【pool-2-thread-3】開始執(zhí)行&hellip;&hellip;
【pool-2-thread-1】開始執(zhí)行&hellip;&hellip;
【pool-2-thread-4】開始執(zhí)行&hellip;&hellip;

CyclicBarrier 示例

所有線程相互等待,直到某一步完成后再繼續(xù)執(zhí)行

        final int totalThread = 3;
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < totalThread; i++) {
            executorService.execute(() -> {
                System.out.println("before..");
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
                System.out.println("after..");
            });
        }
        executorService.shutdown();

打印:

before..
before..
before..
after..
after..
after..

讀到這里,這篇“Java CountDownLatch計數(shù)器與CyclicBarrier循環(huán)屏障怎么定義”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領(lǐng)會,如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI