Cyclicbarrier literal translation called the Circular Barrier, the role of a bit like the whistle-blowing role in the race, it has 2 construction methods, one is the arg1 of int, the other one more runable arg2
Arg1: Can be seen as the number of runners in this race
ARG2: It can be seen as a whistle-blowing action, which is performed before everyone is ready and before running.
1 Public classTest {2 3 Private StaticExecutor Executor =Executors.newcachedthreadpool ();4 5 Public Static voidMain (string[] args)throwsinterruptedexception {6 intSportercount = 5;7Cyclicbarrier Cyclicbarrier =NewCyclicbarrier (Sportercount,NewRunnable () {8 @Override9 Public voidrun () {TenSYSTEM.OUT.PRINTLN ("Blowing black whistle ... "); One } A }); - for(inti = 0; i < Sportercount; i++) { -Executor.execute (NewSporter (i + 1), Cyclicbarrier)); the } - } - } - + - classSporterImplementsRunnable { + A Private intNo; at Privatecyclicbarrier Cyclicbarrier; - - PublicSporter (intNo, Cyclicbarrier cyclicbarrier) { - This. No =No; - This. Cyclicbarrier =Cyclicbarrier; - } in - @Override to Public voidrun () { +System.out.println ("No." + No + "is ready.")); - Try { the This. cyclicbarrier.await ();//Notice the whistle is ready. *}Catch(interruptedexception e) { $ e.printstacktrace ();Panax Notoginseng}Catch(brokenbarrierexception e) { - e.printstacktrace (); the } +System.out.println ("No." + No + "ran"); A } the}
Output Result:
Number 1th is ready, number 4th is ready, 3rd is ready, the 5th is ready, the 2nd is ready to blow the whistle ... Number 2nd has been opened, number 1th has been opened run 4th has been opened run 3rd has run the 5th has been opened
Finally he has a reset () method to reset it so that it continues to be used for the next game ...
This thing is so simple, interested can also look at the internal implementation, is not complicated ~ ~ haha
Java's Cyclicbarrier