An example of of CyclicBarrier for Java concurrent programming

  • 2020-04-01 03:49:26
  • OfStack

Fences are similar to latches, but they are different.

Locks are used to wait for events, while bars are used to wait for other threads. That is to say, the event used to wait is the countDown event, only the countDown event after the execution of all the previous waiting threads can continue to execute; While the fence does not have a countDown event to control the execution of the thread, only the thread's await method can control the execution of the waiting thread.

2. CyclicBarrier emphasizes that there are n threads, and everyone waits for each other. If one thread is not completed, everyone has to wait.

Scenario analysis :10 people go on a spring outing, and they are required to arrive at one place before they can continue their journey. The code is as follows


import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier; class CyclicBarrierWorker implements Runnable {
    private int id;
    private CyclicBarrier barrier;     public CyclicBarrierWorker(int id, final CyclicBarrier barrier) {
        this.id = id;
        this.barrier = barrier;
    }     @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            System.out.println(id + " th people wait");
            barrier.await(); //You wait for the last thread to reach
        } catch (InterruptedException | BrokenBarrierException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
} public class TestCyclicBarrier {
    public static void main(String[] args) {
        int num = 10;
        CyclicBarrier barrier = new CyclicBarrier(num, new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                System.out.println("go on together!");
            }
        });
        for (int i = 1; i <= num; i++) {
            new Thread(new CyclicBarrierWorker(i, barrier)).start();
        }
    }
}

The output

1 th people wait
2 th people wait
3 th people wait
4 th people wait
5 th people wait
7 th people wait
8 th people wait
6 th people wait
9 th people wait
10 th people wait
go on together!


Related articles: