首頁  >  文章  >  Java  >  Java CountDownLatch計數器與CyclicBarrier循環屏障怎麼定義

Java CountDownLatch計數器與CyclicBarrier循環屏障怎麼定義

WBOY
WBOY轉載
2023-05-21 18:25:14712瀏覽

定義

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:計數器,允許一個或多個執行緒等待,直到在其他執行緒中執行的一組操作完成。

CyclicBarrier:循環屏障,它允許一組執行緒相互等待以達到一個共同的屏障點。

區別

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

  • CountDownLatch 的使用場景中,有兩類線程,一類是呼叫await()方法的等待線程,另一類是呼叫countDownl() 方法的操作線程。在 CyclicBarrier 的情境中,所有線程都是等待彼此的線程,屬於同一類型。

  • CountDownLatch 是減計數,遞減完後無法重位,CyclicBarrier 是加計數,遞增完後自動重設

CountDownLatch 範例

建立兩組線程,一組等待另一組執行完才繼續進行

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++) {  //我们要等上面执行完成才继续
    executorService.execute(() -> {
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("await..");
    });
}
executorService.shutdown();

列印:

#run..
run..
run ..
run..
run..
await..
await..
await..

等待累加執行緒執行完,主執行緒再輸出累加結果

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());
    }
}

列印:

#997

3 模擬並發

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() + "】开始执行……");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        Thread.sleep(2000);
        countDownLatch.countDown();//开始并发
        executorService.shutdown();

列印:

#【pool-2-thread-2】開始執行……
【pool-2-thread-5】開始執行……
【pool-2-thread-3】開始執行&hellip ;…
【pool-2-thread-1】開始執行……
【pool-2-thread-4】開始執行……

#CyclicBarrier 範例

所有執行緒互相等待,直到某一步完成後再繼續執行

        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計數器與CyclicBarrier循環屏障怎麼定義的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除