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;
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 cyclicbarrier barrier;
Public Horse (Cyclicbarrier b) {
This.barrier = b;
}
public synchronized int Getstrides () {
return strides;
}
@Override
public void Run () {
try {
while (! Thread.interrupted ()) {
Synchronized (this) {
Strides + = Rand.nextint (3);
}
Barrier.await ();//Cycle wait
}
} catch (Interruptedexception e) {
Todo:handle interruptedexception
} catch (Brokenbarrierexception e) {
throw new RuntimeException (e);
}
}
@Override
Public String toString () {
Return "Horse" + ID + "";
}
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 = 75;
Private listPrivate Executorservice exec = Executors.newcachedthreadpool ();
Private Cyclicbarrier barrier;
Public horserace (int nhorses,final int pause) {
Barrier = new Cyclicbarrier (nhorses,new Runnable () {
@Override
public void Run () {
StringBuilder s = new StringBuilder ();
for (int i = 0; i < finish_line; i++) {
S.append ("=");
}
System.out.println (s);
for (Horse horse:horses) {
System.out.println (Horse.tracks ());
}
for (Horse horse:horses) {
if (Horse.getstrides () >= finish_line) {
System.out.println (horse + "won!");
Exec.shutdownnow ();
Return
}
}
try {
Can sleep, show the effect, otherwise soon after execution, see no obvious effect
TimeUnit.MILLISECONDS.sleep (pause);
} catch (Interruptedexception e) {
System.out.println ("Barrier-behavior Sleep interrupted");
}
}
});
for (int i = 0; i < nhorses; i++) {
Horse Horse = new Horse (barrier);
Horses.add (horse);
Exec.execute (horse);
}
}
public static void Main (string[] args) {
int nhorses = 7;
int pause = 200;
if (Args.length > 0) {
int n = new Integer (args[0]);
nhorses = n > 0? n:nhorses;
}
if (Args.length > 1) {
int p = new Integer (args[1]);
Pause = p > 1? P:pause;
}
New Horserace (nhorses, pause);
}
}
:
Cyclicbarrier------Simulation Horse racing game