The use of Java concurrency Cyclicbarria
I. INTRODUCTION
In writing Countdownlatch This class, I saw the blog park on the "Analysis of Java countdownlatch usage" This blog post, for Bo Master solid technical skills to be impressed, on the Java multithreading is just handy, first of all thank the blogger gave me inspiration, Let me further understand the use of Countdownlatch, please accept the younger brother's knees (if the blogger can see the). Through the "Analysis of Java countdownlatch usage" This blog post, I would like to use this example to say Cyclicbarria usage. Cyclicbarria Chinese translation is "circular fence".
Two. Use of Cyclicbarria
If readers read this article, please first look at the "Analysis of Java in countdownlatch usage" This article, the author only with the help of the blog author, a slight write modification, with Cyclicbarria to achieve. The code is as follows:
Public classCyclicBarriaTest2 {Private Static Final intPlayer_amount = 5;//Five Athletes Private StaticExecutorservice exe =Executors.newfixedthreadpool (Player_amount); Static classCommandImplementsRunnable {Private BooleanFlag; PublicCommand (Booleanflag) { This. Flag =Flag; } @Override Public voidrun () {if(flag) {System.out.println ("The game begins ..."); Flag=false; }Else{System.out.println ("The game is over ..."); Exe.shutdown (); } } } Public Static voidMain (string[] args) {/*** Circular fence. When CB calls the await () method, when 5 threads are all ready, execute the command instantiation of the thread, * when all the threads, execute, and then touch the await () method, wait until all 5 threads are executed, and then execute the command instance * Thread. */Cyclicbarrier CB=NewCyclicbarrier (5,NewCommand (true)); Player[] plays=NewPlayer[player_amount]; for(inti = 0; i < Player_amount; i++) {Plays[i]=NewPlayer (i+1, CB); } for(Player p:plays) {Exe.execute (P); //Assigning Threads } }}
The implementation of the player class is as follows:
classPlayerImplementsrunnable{Private intnum; PrivateCyclicbarrier CB; PublicPlayer (intnum, Cyclicbarrier CB) { This. num =num; This. cb =CB; } @Override Public voidrun () {Try{cb.await (); //wait for all threads to be ready and execute the threads in the CB. Thread.Sleep ((Long) (Math.random () * 100));//randomly allocated time, that is, athlete completion timeSystem.out.println ("Play" + num + "arrived.")); Cb.await (); //when all threads have finished executing, then execute the thread in CB}Catch(Interruptedexception |brokenbarrierexception e) {E.printstacktrace (); } }}
The use of Java concurrency Cyclicbarria