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));
}
}
使用CyclicBarrier类模拟赛跑功能:新建N个人选手,当所有选手准备好时,开始前进一次,每次前进的距离随机在1-3之间,所有选手前进一次后,裁判开始检查有没有到达终点的选手,没有则继续之前操作,直到有一人或多人同时到达终点。2.Person类public class Person extends Thread{ private final String name;