Home > Java > javaTutorial > body text

How to define Java CountDownLatch counter and CyclicBarrier cycle barrier

WBOY
Release: 2023-05-21 18:25:14
forward
752 people have browsed it

Definition

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.

The above is the official definition of Oracle. In simple terms

CountDownLatch: Counter that allows one or more threads to wait until a set of operations performed in other threads is completed.

CyclicBarrier: Cyclic Barrier, which allows a group of threads to wait for each other to reach a common barrier point.

Difference

  • CountDownLatch is a member of AQS (AbstractQueuedSynchronizer), but CyclicBarrier is not.

  • In the usage scenario of CountDownLatch, there are two types of threads, one is the waiting thread that calls the await() method, and the other is the operating thread that calls the countDownl() method. In the context of CyclicBarrier, all threads are threads waiting for each other and are of the same type.

  • CountDownLatch is a down count, which cannot be reset after the decrement is completed. CyclicBarrier is an up count, which is automatically reset after the increment is completed.

CountDownLatch example

Create two groups of threads, one group waits for the other group to finish executing before continuing

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();
Copy after login

Print:

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

Wait for the accumulation thread to finish executing, and then the main thread Output cumulative results

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

Print:

997

3 Simulate concurrency

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();
Copy after login

Print:

【pool-2-thread-2】Start execution...
【pool-2-thread-5】Start execution... ;…
【pool-2-thread-1】Start execution……
【pool-2-thread-4】Start execution...

All threads wait for each other until a certain step is completed before continuing
        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();
Copy after login

Print:

before..

before..

before ..
after..

after..
after..

The above is the detailed content of How to define Java CountDownLatch counter and CyclicBarrier cycle barrier. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template