Cyclicbarrier means a fence that allows multiple groups of threads to arrive at a point and wait until the specified number of threads arrives and then resumes the thread, a cyclicbarrier that can be reused. Also known as the circular fence.
Chestnuts:
Public classBarrierdemo { Public Static voidMain (string[] args) {Executorservice service= Executors.newfixedthreadpool (5); FinalCyclicbarrier barrier =NewCyclicbarrier (5); for(inti = 0; I < 5; i++) {Service.execute (NewPlayer ("player" +I, barrier)); } service.shutdown (); }} Public classPlayerImplementsRunnable {Private FinalString name; Private Finalcyclicbarrier Barrier; PublicPlayer (String name, Cyclicbarrier barrier) { This. Name =name; This. Barrier =barrier; } Public voidrun () {Try{TimeUnit.SECONDS.sleep (1 + (NewRandom (). Nextint (3))); SYSTEM.OUT.PRINTLN (Name+ "Ready, wait for other players to prepare ..."); barrier.await (); TimeUnit.SECONDS.sleep (1 + (NewRandom (). Nextint (3))); SYSTEM.OUT.PRINTLN (Name+ "joined the game"); } Catch(interruptedexception e) {System.out.println (name+ "Leave the game"); } Catch(brokenbarrierexception e) {System.out.println (name+ "Leave the game"); } }}
Cyclicbarrier has two constructors:
public Cyclicbarrier (int parties)
public Cyclicbarrier (int parties, Runnable barrieraction)
The parties parameter specifies the number of threads, and when the specified thread value reaches the fence point, the fence opens and the thread resumes. It is important to note that when the number of threads specified is greater than the number of threads started, such as modifying the code in the previous example to start only 9 threads, all threads will remain in the waiting state. The second case is that the specified number of threads is less than the thread that was started, the example code, starting 11 threads, then when the tenth thread arrives at the fence point, then the 10 threads will resume execution and the 11th thread will remain in a blocked state.
Cyclicbarrier also provides a higher-level constructor Cyclicbarrier (int parties, Runnable barrieraction), which performs barrieraction when the thread arrives at the barrier, Facilitates handling of more complex business scenarios.
Methods of Cyclicbarrier:
1. Await () Use this method to cause the current thread to block at the fence point and wait for all threads.
2. Await (long timeout, timeunit unit) increases the timeout parameter, and waits for a timeout to throw an exception.
3. Getnumberwaiting () returns the number of participants currently waiting at the fence. This method is primarily used for debugging and assertions.
4. Getparties () This method can get the number of threads specified in the constructor that need to be blocked at the fence point
A brief talk on Java Cyclicbarrier