Cyclicbarrier class:
Original: A synchronous helper class that allows a group of threads to wait until they reach a common barrier point (common barrier points). 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 .
Speaking: it can block multiple threads, calling Cyclicbarrier's await () method to keep the thread waiting until all threads reach the barrier and then wake up.
Cyclicbarrier provides 2 construction methods:
Cyclicbarrier(int parties)
Cyclicbarrier(int parties, Runnable barrierAction)
The following example uses the second construction method to simulate 10 snipers in place, and if 10 snipers are already in place, report to the Commander, and the Commander orders to shoot.
Public classDemo { Public Static voidMain (string[] args) {//definition of 10 snipers intThreadnum = 10; //Instantiate a cyclicbarrier (loop barrier)Cyclicbarrier Cyclicbarrier =NewCyclicbarrier (Threadnum,NewRunnable () {@Override Public voidrun () {System.out.println ("Person in charge: report commander, all snipers are in place." "); System.out.println ("Commander: Action! "); } }); //Add 10 threads to a simulation for(intI=1; i<=threadnum; i++){ NewThread (NewSniper (Cyclicbarrier, "Sniper" + i + "No.") . Start (); } }}
Define a sniper class and implement the Runnable interface.
Public classSniperImplementsRunnable {PrivateCyclicbarrier Cyclicbarrier; PrivateString name; PublicSniper (cyclicbarrier cyclicbarrier, String name) { This. Cyclicbarrier =Cyclicbarrier; This. Name =name; } @Override Public voidrun () {Try { //random 0-10 seconds to simulate the sniper's position.Random ran =NewRandom (); intMillisecond = (Ran.nextint (10) + 1); intSecond = millisecond * 1000; Thread.Sleep (second); //the report is in place when you're ready.SYSTEM.OUT.PRINTLN (name + ": Already in place, spents" + millisecond + "seconds.) "); //Call the Cyclicbarrier.await () method to waitcyclicbarrier.await (); //Sniper Strike TargetSYSTEM.OUT.PRINTLN (name + ": report," + (millisecond% 2 = = 1?) "The enemy has been killed." ":" was not hit. ")); } Catch(interruptedexception e) {e.printstacktrace (); } Catch(brokenbarrierexception e) {e.printstacktrace (); } }}
The effect is as follows:
Java.util.concurrent Cyclicbarrier Class