Java concurrency tool CyclicBarrier
CyclicBarrier synchronization barrier
The java concurrency tool class has a class called javasicbarrier. Similar to CountDownLatch, it can synchronize threads. However, the difference is that javasicbarrier is a pluggable synchronization barrier.
Imagine a scenario where N people go to a door at different times, because it takes N people to work together to open the door, so when there are less than N people, they can only be blocked here, when N people arrive, they can open the door and continue their work. CyclicBarrier is the door.
Take a look at the following code and define a javasicbarrier with 2 threads, and call await in the main thread and another thread to block it:
import java.util.concurrent.BrokenBarrierException;import java.util.concurrent.CyclicBarrier;public class Main { static CyclicBarrier cyclicBarrier = new CyclicBarrier(2); public static void main(String[] args) throws InterruptedException, BrokenBarrierException{ new Thread(new Runnable() { @Override public void run() { System.out.println(thread 1 start); try { cyclicBarrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } System.out.println(thread 1 end); } }).start(); System.out.println(thread 2 start); cyclicBarrier.await(); System.out.println(thread 2 end); }}
According to the thread scheduling order, there are multiple execution results, one of which is:
Thread 2 start
Thread 1 start
Thread 1 end
Thread 2 end
However, the common effect of all execution is that all threads must be blocked at the await synchronization point before they can proceed to the next step.
You can call the reset () method of javasicbarrier to reset it, so that you can perform error recovery and other operations in complex scenarios.
In addition, CyclicBarrier has the following constructor:
public CyclicBarrier(int parties, Runnable barrierAction) { if (parties <= 0) throw new IllegalArgumentException(); this.parties = parties; this.count = parties; this.barrierCommand = barrierAction; }
You can provide a Runnable parameter to prioritize barrierAction when the threads reach the barrierAction.