Cyclicbarrier Synchronization Barrier
There is a class called Cyclicbarrier in the Java Concurrency Tool class, similar to Countdownlatch, where synchronization between threads is possible, but the difference is that Cyclicbarrier is a reset synchronization barrier.
Imagine a scene, there are n people to go to a door at different times, because the door needs n personal force to push, so people less than n when, can only block here, until the N people have arrived, you can push the door, continue to work before. Cyclicbarrier is the door.
Take a look at the following code, which defines a thread number of 2, cyclicbarrier, and calls await in the main thread and another thread to block:
ImportJava.util.concurrent.BrokenBarrierException;ImportJava.util.concurrent.CyclicBarrier; Public class Main { StaticCyclicbarrier Cyclicbarrier =NewCyclicbarrier (2); Public Static void Main(string[] args)throwsInterruptedexception, brokenbarrierexception{NewThread (NewRunnable () {@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"); }}
Depending on the order of thread scheduling, there are multiple execution results, one is:
Thread 2 Start
Thread 1 start
Thread 1 End
Thread 2 End
However, the common denominator of all execution effects is that all threads must be blocked by the await synchronization point before the next action can be performed.
You can call the Reset () method of Cyclicbarrier to reset it to perform operations such as error recovery in complex scenes.
In addition, Cyclicbarrier has the following constructors:
publicCyclicBarrier(int parties, Runnable barrierAction) { if0thrownew IllegalArgumentException(); this.parties = parties; this.count = parties; this.barrierCommand = barrierAction; }
You can provide a runnable parameter that takes precedence over barrieraction when the thread reaches the barrier.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java Concurrency Tool class Cyclicbarrier