Cyclicbarrier is a synchronization helper class under the Java.util.concurrent package, similar to Countdownlatch, and is also a synchronization counter.
The difference between Countdownlatch and the other is:
The Countdownlatch await () method is blocked because the countdown () method that waits for a certain number of calls can be done on the same thread;
The Cyclicbarrier await () method is blocked because a certain number of threads are waiting to invoke the await () method, which must be called on a different thread
So, to summarize:
Countdownlatch is waiting for a certain number of calls to Countdown (), otherwise the thread that calls the await () method is blocked.
Cyclicbarrier is waiting for a certain number of threads to call await (), otherwise all threads calling await () will block.
Demo Code:
import java.util.random;import java.util.concurrent.brokenbarrierexception;import java.util.concurrent.cyclicbarrier;import java.util.concurrent.executorservice;import java.util.concurrent.executors; public class testcyclicbarrier { public static void main (String[] args) { executorservice exec = executors.newcachedthreadpool (); /** * indicates that the Cyclicbarrier await () method must be performed on every 5 threads, to execute the Run method in Cyclicbarrier; * if there are less than 5 threads executing the await () method, then the thread that executes the await () method will block, until the 5th thread executes the await () method; */ final cyclicbarrier Cyclicbarrier = new cyclicbarrier (5, new runnable () { public void run () { system.out.println ("Everybody's Here, start Happy"); } }); final random random=new random (); for (int i = 0; i < 5; i++) { &nbsP; exec.execute (new runnable () { public void run () { try { thread.sleep (RANDOM.NEXTINT (1000 )); } catch (interruptedexception e) { e.printstacktrace (); } system.out.println ( Thread.CurrentThread (). GetName () + "Come, Other buddies"); try { //waits for the remaining threads to execute the await () method; cyclicbarrier.await (); } catch (InterruptedException e) { e.printstacktrace (); } catch (brokenbarrierexception e) { E.printstacktrace (); } system.out.println (Thread.currentThread (). GetName ( + "Say: people qi, play to go ..."); } }); &nBsp; } exec.shutdown () ; } }
This article is from the "Deaconli" blog, make sure to keep this source http://lizhuquan0769.blog.51cto.com/2591147/1788538
"Java Multithreading" Cyclicbarrier Synchronization helper Class