public class Person extends Thread{
private final String name;
private CyclicBarrier cb;
//本次前进之后的总距离
private int now;
public Person(String name,CyclicBarrier cb){
this.name = name;
this.cb = cb;
}
public synchronized int getNow(){
return now;
}
public synchronized String getPersonName(){
return name;
}
@Override
public void run(){
while(true){
try {
cb.await();
int random = (int)(Math.random()*3+1);
synchronized (this) {
now += random;
System.out.println(name +"本次跑了 "+random+" 米,共跑了 "+now+" 米");
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}
}
3.Judge类
public class Judge extends Thread{
private static final int MAX = 100;
private CopyOnWriteArrayList<Person> cowl;
public synchronized void setCowl(CopyOnWriteArrayList<Person> cowl){
this.cowl = cowl;
}
private void judge(){
System.out.println("\n==============start judge=================");
/*
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
List<Person> list = new ArrayList<>();
for(Person p :cowl){
if(p.getNow()>=MAX)
list.add(p);
}
if(list.size()!=0){
for(Person p:list)
System.out.println(p.getPersonName()+"率先抵达终点!");
System.exit(0);
}
System.out.println("\n==============end judge=================");
}
@Override
public void run() {
judge();
}
}
4.测试启动类
public class CyclicBarrierTest {
public static void main(String[] args) {
Judge judge = new Judge();
CyclicBarrier cb = new CyclicBarrier(10, judge);
List<Person> list = new ArrayList<>();
for(int i=0;i<10;i++){
Person p = new Person("tom"+i,cb);
p.start();
list.add(p);
}
judge.setCowl(new CopyOnWriteArrayList<>(list));
}
}