1. Introduction and source code Analysis of Cyclicbarrier
Cyclicbarrier literally means a barrier (Barrier) that can be recycled (Cyclic). What it does is to block a group of threads from reaching a barrier (also called a sync point), until the last thread reaches the barrier, the barrier opens, and all the threads that are blocked by the barrier continue to work. The thread enters the barrier through the Cyclicbarrier await () method.
Cyclicbarrier the default constructor is cyclicbarrier (int parties), whose parameters represent the number of threads that the barrier intercepts, and each thread calls the await method to tell Cyclicbarrier I have reached the barrier, and then the current thread is blocked.
Cyclicbarrier also provides a more advanced constructor cyclicbarrier (int parties, Runnable barrieraction) for when the thread reaches the barrier, Prioritize barrieraction this Runnable object for easier handling of more complex business scenarios.
constructor function
Public Cyclicbarrier (int parties) {This null);} Public int getparties () { return parties;}
Implementation principle: Within the Cyclicbarrier defines a lock object, each time a thread calls the Cyclicbarrier await method, the remaining number of blocked threads minus 1, and then determine whether the remaining interception number is 0, if not, Waits for the conditional queue that enters the lock object. If so, execute the Runnable method of the Barrieraction object, and then place all the threads in the lock's conditional queue into the lock waiting queue, which take the lock, release the lock in turn, and then return from the await method. And return from the await method of the cyclicbarrier.
Await source
Public int throws Interruptedexception, brokenbarrierexception { try { return dowait (false, 0L); Catch (TimeoutException toe) { thrownew//Cannot happen }}
Dowait Source
Private intDowait (BooleanTimedLongNanosthrowsInterruptedexception, Brokenbarrierexception, timeoutexception {FinalReentrantlock lock = This. Lock; Lock.lock ();Try{FinalGeneration g = Generation;if(G.broken)Throw NewBrokenbarrierexception ();if(Thread.interrupted ()) {Breakbarrier ();Throw NewInterruptedexception (); }intindex =--count;if(index = = 0) {//Tripped BooleanRanaction =false;Try{FinalRunnable command = Barriercommand;if(Command! =NULL) Command.run (); Ranaction =true; Nextgeneration ();return0; }finally{if(!ranaction) Breakbarrier (); } }//Loop until tripped, broken, interrupted, or timed out for(;;) {Try{if(!timed) trip.await ();Else if(Nanos > 0L) Nanos = Trip.awaitnanos (Nanos); }Catch(Interruptedexception IE) {if(g = = Generation &&! G.broken) {Breakbarrier ();ThrowKey }Else{//We ' re about-to-finish waiting even if We had not //been interrupted, so this interrupt are deemed to //"belong" to subsequent execution.Thread.CurrentThread (). interrupt (); } }if(G.broken)Throw NewBrokenbarrierexception ();if(g! = Generation)returnIndexif(Timed && Nanos <= 0L) {Breakbarrier ();Throw NewTimeoutException (); } } }finally{Lock.unlock (); }}
When the last thread reaches the barrier point, that is, when the Dowait method is executed, the Breakbarrier method in the finally block is called before return 0 returns.
Breakbarrier Source Code
Private void breakbarrier () { true; Count = parties; Trip.signalall ();}
Cyclicbarrier is primarily used for mutual waits between a set of threads, while Countdownlatch is typically used for a group of threads waiting for another set of threads. the function of cyclicbarrier can actually be achieved through Countdownlatch's countdown () and await (). That is, Countdown () +await () in Countdownlatch = await () in Cyclicbarrier. Note: Call Countdown () first in a thread, and then call await ().
Other methods: The Cyclibarrier object can be reused, reusing the reset method that should have called the Cyclicbarrier object before it is reused.
Reset Source
Public void Reset () { finalthis. Lock; Lock.lock (); Try { breakbarrier (); // Break the current generation //Start a new generation finally { lock.unlock (); }}
2. Using the example
Packagejavalearning;ImportJava.util.Random;ImportJava.util.concurrent.BrokenBarrierException;ImportJava.util.concurrent.CyclicBarrier;ImportJava.util.concurrent.ExecutorService;ImportJava.util.concurrent.Executors; Public classCyclicbarrierdemo {PrivateCyclicbarrier cb =NewCyclicbarrier (4);PrivateRandom rnd =NewRandom ();classTaskdemoImplementsrunnable{PrivateString ID; Taskdemo (String ID) { This. id = ID;} @Override Public voidRun () {Try{Thread.Sleep (Rnd.nextint (1000)); System.out.println ("Thread"+ ID +"Would wait"); cb.await (); System.out.println ("-------Thread"+ ID +" is Over");}Catch(Interruptedexception e) {}Catch(Brokenbarrierexception e) {}}} Public Static voidMain (string[] args) {Cyclicbarrierdemo CBD =NewCyclicbarrierdemo (); Executorservice es = Executors.newcachedthreadpool (); Es.submit (CBD.NewTaskdemo ("a")); Es.submit (CBD.NewTaskdemo ("b")); Es.submit (CBD.NewTaskdemo ("C")); Es.submit (CBD.NewTaskdemo ("D")); Es.shutdown ();}}
In this example, we created four threads A, B, C, D, and these four line Chengti are given to the thread pool. Four threads arrive at the cb.await () statement at different times, and when four threads output "thread X will wait" the output is "thread X was over".
Run results
Thread D would wait
Thread a'll wait
Thread C would wait
Thread B would wait
-------Thread B is over
-------Thread D is over
-------Thread A is over
-------Thread C is over 3. Reference content
[1] http://ifeve.com/concurrency-cyclicbarrier/
How Cyclicbarrier works and uses examples in Java and contract