Cyclicbarrier literally means a reusable barrier whose main purpose is to block a group of threads from reaching a barrier, knowing that the barrier will open when the last thread reaches the barrier, and that all the threads that are blocked by the barrier will continue to run.
1, Introduction:
Cyclicbarrier the default constructor is cyclicbarrier (int parties), where the parameters identify the number of threads intercepted by the barrier, and each thread calls the await method to tell Cyclicbarrier I have reached the barrier, and then the current thread is blocked.
Packagecom.test;ImportJava.util.concurrent.CyclicBarrier; Public classCiclicbarriertest {StaticCyclicbarrier C =NewCyclicbarrier (2); Public Static voidMain (string[] args) {NewThread (NewRunnable () {@Override Public voidrun () {Try{c.await (); } Catch(Exception e) {e.printstacktrace (); } System.out.println (1); }}). Start (); Try{c.await (); } Catch(Exception e) {e.printstacktrace (); } System.out.println (2); }}
If you modify new Cyclicbarrier (2) to erase new Cyclicbarrier (3), the main thread and the child thread will wait forever because there is no third thread to execute the await method. Neither of the third threads reached the barrier, so the two threads that reached the barrier did not continue to execute.
Cyclicbarrier also provides a higher-level constructor, Cyclicbarrier (int parties, Runnable barrier-action) to perform barrieraction when the thread arrives at the barrier, Facilitates handling of more complex business scenarios:
Packagecom.test;ImportJava.util.concurrent.CyclicBarrier; Public classCiclicbarriertest {StaticCyclicbarrier C =NewCyclicbarrier (2,NewA ()); Public Static voidMain (string[] args) {NewThread (NewRunnable () {@Override Public voidrun () {Try{c.await (); } Catch(Exception e) {e.printstacktrace (); } System.out.println (1); }}). Start (); Try{c.await (); } Catch(Exception e) {e.printstacktrace (); } System.out.println (2); } Public Static classAImplementsRunnable {@Override Public voidrun () {System.out.println (3); } }}//Results312
The difference between Cyclicbarrier and Countdownlatch:
Countdownlatch counters can only be used once, while cyclicbarrier counters may be reset using the Reset () method. So cyclicbarrier can handle more complex business scenarios.
Cyclicbarrier also provides other useful methods, such as the Getnumberwaiting method, to get the number of blocked threads. The IsBroken () method is used to understand whether the blocked thread is interrupted.
Java Cyclicbarrier Synchronization Barrier