Using javasicbarrier, a component in the new java Thread class library
Package org. rui. thread. newc; import java. util. arrayList; import java. util. list; import java. util. random; import java. util. concurrent. brokenBarrierException; import java. util. concurrent. cyclicBarrier; import java. util. concurrent. executorService; import java. util. concurrent. executors; import java. util. concurrent. timeUnit;/*** Horse racing game javasicbarrier ** @ author lenovo **/class Horse implements Runnable {private Static int counter = 0; private final int id = counter ++; private int strides = 0; private static Random rand = new Random (47); private static policicbarrier barrier; public Horse (CyclicBarrier B) {barrier = B;} public synchronized int getStrides () {return strides ;}@ Overridepublic void run () {try {while (! Thread. interrupted () {synchronized (this) {// random numbers 0, 1 or 2 strides + = rand are added to each game. nextInt (3); // produces or 2} // wait until all horses are ready. When all horses move forward, javasicbarrier automatically calls the runnable fence action task, the position of the horse and the terminal is displayed in order. await () ;}} catch (InterruptedException e) {}catch (BrokenBarrierException e) {throw new RuntimeException (e) ;}} public String toString () {return "Horse" + id + "" ;}// track public String tracks () {StringBuilder s = new StringBuilder (); for (int I = 0; I <getStrides (); I ++) {s. append ("*");} s. append (id); return s. toString () ;}} public class HorseRace {static final int FINISH_LINE = 15; // end line private List
Horses = new ArrayList
(); Private ExecutorService exec = Executors. newCachedThreadPool (); private javasicbarrier barrier; public HorseRace (int nHorses, final int pause) {barrier = new javasicbarrier (nHorses/* Number of waits */, new Runnable () {@ Overridepublic void run () {// print information StringBuilder sb = new StringBuilder (); for (int I = 0; I <FINISH_LINE; I ++) {sb. append ("="); // barrier on the racecourse} System. out. println (sb); for (Horse horse: horses) {lead E M. out. println (horse. tracks ();} for (Horse horse: horses) {// System. out. println ("strides:" + horse. getStrides (); if (horse. getStrides ()> = FINISH_LINE) {// System. out. println (horse + "win! "); Exec. shutdownNow (); return ;}} try {TimeUnit. MILLISECONDS. sleep (pause);} catch (InterruptedException e) {System. out. println ("barrier-action sleep interrupted") ;}}}); // once all the horses have crossed the fence, it automatically prepares for the next round of competition (int I = 0; I <nHorses; I ++) {Horse horse = new Horse (barrier ); // each horse is allocated with a barrierhorses.add(horsespontesexec.exe cute (horse) ;}/ *** main *** @ param args */public static void main (String [] args) {int nHors Es = 7; // The number of specified horses int pause = 200; // pause time String [] arg ={}; if (arg. length> 0) {// optional argumentint n = new Integer (arg [0]); nHorses = n> 0? N: nHorses;} if (arg. length> 1) {// optional argumentint p = new Integer (arg [1]); pause = p>-1? P: pause;} // competition new HorseRace (nHorses, pause );}} /** =================================================== ========================================================= ** 0 ** 1*2 ** 3*4 ** 5*6 ========================== ========================================================== ============ ** 0 *** 1 ** 2 ** 3*4 ** 5 ** 6 ======== ========================================================== ====================================== ** 0 ***** 1 *** 2 *** 3 *** 4 ******* 5 ***** 6 ========================= ========================================================== ===================******* 0 ****** 1 ******* 2 ****** 3 **** 4 * * 5*6 = ========================================================== ====== ******* 0 ****** 1 ******** 2 ******** 3 ****** 4 **** ** 5 ***** 6 ======================================== ========================================================== ==== *** * 5*6 = ========================================================== ====== **** * 4*5*6 = ========================================================== ===================********** 0 ******************* 2 * ********************************** 6 ==== ========================================================== ====================================== ******** 0 * * 1*2*3*4 ****** * ** 5 ********* 6 ========================== ========================================================== ========== ************0 ******************* 2 * * ************************************* 6 ========================================================== ================================================================ ***** *** * 6 = ========================================================== ============================================************ 0 * * 1*2*3 ******* * ** 4 ***************** 5 ************ 6 ======== ========================================================== ====================================== *********** 0*1 *** * ========================================================== ============================================================ ****** ******** * ***** 3 **************** 4 ......
... Print line =================================================== ========================================================= ** **************************************** *********** **************************************** *********************************** ******** **************************************** **************** ********************************** ********************* 4 ****************** **************************************** ************************** * ********************************** 6 = ========================================================== ============================================ ********* **************************************** ***************** ************************************* 1 * **************************************** ************* **************************************** ******************* **************************************** *************************** **************************************** ********************************* * 6 = ========================================================== ============================================ ************** **************************************** ********************* * *********************************** 1 **** **************************************** * ********************** 2 **************** **************************************** ******************** **************************************** **************************** **************************************** ******************************** ******************************** 6Horse3 win! */
An easy-to-understand example
Package test; import java. util. concurrent. brokenBarrierException; import java. util. concurrent. cyclicBarrier; import java. util. concurrent. executorService; import java. util. concurrent. executors;/*** CyclicBarrier application * @ author lenovo **/public class javasicbarriertest {public static void main (String [] args) {ExecutorService service = Executors. newCachedThreadPool (); final CyclicBarrier cb = new CyclicBarr Ier (3); // three threads simultaneously reach for (int I = 0; I <3; I ++) {Runnable runnable = new Runnable () {public void run () {try {Thread. sleep (long) (Math. random () * 10000); System. out. println ("Thread" + Thread. currentThread (). getName () + "coming to collection location 1, current" + (cb. getNumberWaiting () + 1) + "arrived" + (cb. getNumberWaiting () = 2? "It's all here. Continue.": "Waiting"); try {cb. await ();} catch (BrokenBarrierException e) {e. printStackTrace ();} Thread. sleep (long) (Math. random () * 10000); System. out. println ("Thread" + Thread. currentThread (). getName () + "coming to collection Location 2, current" + (cb. getNumberWaiting () + 1) + "arrived" + (cb. getNumberWaiting () = 2? "It's all here. Continue.": "Waiting"); try {cb. await ();} catch (BrokenBarrierException e) {e. printStackTrace ();} Thread. sleep (long) (Math. random () * 10000); System. out. println ("Thread" + Thread. currentThread (). getName () + "coming to collection location 3, current" + (cb. getNumberWaiting () + 1) + "arrived" + (cb. getNumberWaiting () = 2? "It's all here. Continue.": "Waiting"); try {cb. await ();} catch (BrokenBarrierException e) {e. printStackTrace () ;}} catch (InterruptedException e) e.printstacktrace({%}%%%%service.exe cute (runnable);} service. shutdown () ;}/ *** output: thread pool-1-thread-3 is about to arrive at collection location 1, one already exists waiting for thread pool-1-thread-1 to reach collection location 1, currently, two threads have arrived, waiting for thread pool-1-thread-2 to arrive at collection location 1. Currently, three threads have arrived, continue here. thread pool-1-thread-2 is about to arrive at the collection site 2. Currently, one has arrived at the waiting thread pool-1-thread-1 and is about to arrive at the collection site 2, currently, two threads have arrived at the waiting thread pool-1-thread-3, which is about to arrive at the collection site 2. Currently, three threads have arrived, continue. thread pool-1-thread-3 is about to arrive at the collection site 3. Currently, one has arrived at the waiting thread pool-1-thread-2 is about to arrive at the collection site 3, currently, two threads have arrived at the waiting thread pool-1-thread-1, which is about to arrive at the collection site 3. Currently, three threads have arrived at the same time. Continue */