http://www.jianshu.com/p/1716ce690637
public class Athlete implements Runnable {
private CyclicBarrier cyclicBarrier;
private String name;
public Athlete(CyclicBarrier cyclicBarrier, String name) {
this.cyclicBarrier = cyclicBarrier;
this.name = name;
}
@Override
public void run() {
System.out.println(name + "就位");
try {
cyclicBarrier.await();
Random random = new Random();
double time = random.nextDouble() + 9;
System.out.println(name + ": " + time);
} catch (Exception e) {
}
}
}
public class Race {
private CyclicBarrier cyclicBarrier = new CyclicBarrier(8);
public void start() {
List<Athlete> athleteList = new ArrayList<>();
athleteList.add(new Athlete(cyclicBarrier,"博尔特"));
athleteList.add(new Athlete(cyclicBarrier,"鲍威尔"));
athleteList.add(new Athlete(cyclicBarrier,"盖伊"));
athleteList.add(new Athlete(cyclicBarrier,"布雷克"));
athleteList.add(new Athlete(cyclicBarrier,"加特林"));
athleteList.add(new Athlete(cyclicBarrier,"苏炳添"));
athleteList.add(new Athlete(cyclicBarrier,"路人甲"));
athleteList.add(new Athlete(cyclicBarrier,"路人乙"));
Executor executor = Executors.newFixedThreadPool(8);
for (Athlete athlete : athleteList) {
executor.execute(athlete);
}
}
public static void main(String[] args) {
new Race().start();
}
}
博尔特就位
鲍威尔就位
布雷克就位
盖伊就位
加特林就位
苏炳添就位
路人乙就位
路人甲就位
路人甲: 9.51226151810757
博尔特: 9.642638199239414
鲍威尔: 9.43763463133346
布雷克: 9.434973837687593
盖伊: 9.066815226686979
加特林: 9.752555541261309
苏炳添: 9.152970744830995
路人乙: 9.45883273627546