HorseRace.java
每个horse每走一步,都会停下来等待其他horse完成这一步操作
cyclicBarrier的线程会在每一步所有horse完成操作后执行一次
package com.test.concurrent;
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;
public class HorseRace {
static final int FINISH_LINE=75;
private List<Horse> horses=new ArrayList<Horse>();
private ExecutorService exec=Executors.newCachedThreadPool();
private CyclicBarrier barrier;
public HorseRace(int nHorses, final int pause){
/*CyclicBarrier</tt> that will trip when the
* given number of parties (threads) are waiting upon it, and which
* will execute the given barrier action when the barrier is tripped,
* performed by the last thread entering the barrier.
*/
barrier=new CyclicBarrier(nHorses,new Runnable(){
public void run(){
StringBuilder sb=new StringBuilder();
for(int i=0;i<FINISH_LINE;i++){
sb.append("=");
}
System.out.println(sb.toString());
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 {
TimeUnit.MILLISECONDS.sleep(pause);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("barrier-action sleep interrupted");
e.printStackTrace();
}
}
});
for(int i=0;i<nHorses;i++){
Horse horse=new Horse(barrier);
horses.add(horse);
exec.execute(horse);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new HorseRace(7,200);
}
}
class Horse implements Runnable{
@Override
public void run(){
try {
while(!Thread.interrupted()){
synchronized(this){
strides+=rand.nextInt(3);
}
barrier.await();
}
} catch (InterruptedException | BrokenBarrierException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String tracks() {
// TODO Auto-generated method stub
StringBuilder sb=new StringBuilder();
for(int i=0;i<getStrides();i++){
sb.append("*");
}
sb.append(id);
return sb.toString();
}
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){
barrier=b;
}
public synchronized int getStrides(){
return strides;
}
public String toString(){
return "Horse id: "+id;
}
}