首頁 > Java > java教程 > Java CountDownLatch計數器與CyclicBarrier循環屏障怎麼定義

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

WBOY
發布: 2023-05-21 18:25:14
轉載
781 人瀏覽過

定義

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
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板