Cyclicbarrier is a synchronous helper class, and the main function is to let a group of threads wait for each other, knowing that all arrive at a common barrier and walk together. 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 support for Runnable
an optional command, after the last thread in a group of threads arrives (but before releasing all threads), the command runs only once at each barrier point. This barrier operation is useful if you update the shared state before continuing with all participating threads .
ImportJava.util.Random;Importjava.util.concurrent.BrokenBarrierException;ImportJava.util.concurrent.CyclicBarrier;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors; Public classCyclicbarriertest { Public Static voidMain (string[] args) {Executorservice Newcachedthreadpool=Executors.newcachedthreadpool (); FinalCyclicbarrier Cyclicbarrier =NewCyclicbarrier (3); for(inti = 0; I < 3; i++) {Runnable Runnable=NewRunnable () {@Override Public voidrun () {Try{Thread.Sleep (NewRandom (). Nextint (10000)); System.out.println ("Thread" +thread.currentthread (). GetName () + "Approaching 1, currently available" + (cyclicbarrier.getnumberwaiting () +1) + "reached" + ( Cyclicbarrier.getnumberwaiting () ==2? " It's all here, keep going, "wait.")); Cyclicbarrier.await (); Thread.Sleep (NewRandom (). Nextint (10000)); System.out.println ("Thread" +thread.currentthread (). GetName () + "Approaching 2, currently available" + (cyclicbarrier.getnumberwaiting () +1) + "reached" + ( Cyclicbarrier.getnumberwaiting () ==2? " It's all here, keep going, "wait.")); Cyclicbarrier.await (); Thread.Sleep (NewRandom (). Nextint (10000)); System.out.println ("Thread" +thread.currentthread (). GetName () + "Approaching 3, currently available" + (cyclicbarrier.getnumberwaiting () +1) + "reached" + ( Cyclicbarrier.getnumberwaiting () ==2? " It's all here, keep going, "wait.")); Cyclicbarrier.await (); } Catch(interruptedexception e) {e.printstacktrace (); } Catch(brokenbarrierexception e) {e.printstacktrace (); } } }; Newcachedthreadpool.execute (runnable); } newcachedthreadpool.shutdown (); //Close the thread pool when execution is complete } }
Java Thread Sync helper class Cyclicbarrier loop barrier