Java.util.concurrent.CylicBarrier is a synchronous helper class that allows a set of threads to wait for each other until a common barrier point (common barrier points) is reached. In programs that involve a set of fixed-size threads, these threads have to wait for each other, and cyclicbarrier is useful at this time. Because the barrier can be reused after releasing the waiting thread, it is called a cyclic barrier. Cyclicbarrier supports an optional Runnable command that runs only once at each barrier point after the last thread in a set of threads arrives (but before releasing all threads). This barrier operation is useful if you update the shared state before continuing with all participating threads.
Main methods:
Set size, that is, the number of threads
1.CyclicBarrier (int)
2. When the number of await has reached the set number, the Runnable object is executed first: Cyclicbarrier (int,runnable)
3. Notification barrier completed thread: await ()
Package Cn.baokx;import Java.util.random;import Java.util.concurrent.brokenbarrierexception;import Java.util.concurrent.cyclicbarrier;import Java.util.concurrent.timeunit;class WorkThread implements Runnable { private static int work_num = 4;private cyclicbarrier cb;private string name;public workthread (cyclicbarrier cb, String NA Me) {THIS.CB = Cb;this.name = name;} @Overridepublic void Run () {try {TimeUnit.SECONDS.sleep (New Random (). Nextint (10)); System.out.println (THIS.name + "completed first phase of work"); if (cb.getnumberwaiting () = = (work_num-1)) {System.out.println (" We all completed the first phase of the work, preparing for the second phase of the work to commence ... ");} try {cb.await ();} catch (Brokenbarrierexception e) {e.printstacktrace ();} TimeUnit.SECONDS.sleep (New Random (). Nextint (10)); System.out.println (THIS.name + "completed Phase II work"); if (cb.getnumberwaiting () = = (work_num-1)) {System.out.println (" We all completed the second phase of the work, preparing for the third phase of the work to commence ... ");} try {cb.await ();} catch (Brokenbarrierexception e) {e.printstacktrace ();} TimeUnit.SECONDS.sleep (New Random (). Nextint (10)); System.out.println (thIs.name + "Completed Phase III work"); if (cb.getnumberwaiting () = = (work_num-1)) {System.out.println ("Everyone has completed the third stage of work ... "); System.out.println ("The company leader is quite satisfied, the whole holiday week ... ");} try {cb.await ();} catch (Brokenbarrierexception e) {e.printstacktrace ();}} catch (Interruptedexception e) {e.printstacktrace ();}}} public class Cyclicbarriertest {public static void main (string[] args) {Cyclicbarrier cb = new Cyclicbarrier (4); new Thread (New Workthread (CB, "Zhangsan")). Start (), New Thread (new Workthread (CB, "Lisi")). Start (); New Thread (New Workthread (CB, "Wangwu"). Start (); New Thread (New Workthread (CB, "Zhaoliu")). Start ();}}
Basic usage of Java multi-thread Cyclicbarrier class