Java 同步器
CyclicBarrier是什么
CyclicBarrier也叫同步屏障,在JDK1.5被引入,可以让一组线程达到一个屏障时被阻塞,直到最后一个线程达到屏障时,所以被阻塞的线程才能继续执行。
CyclicBarrier好比一扇门,默认情况下关闭状态,堵住了线程执行的道路,直到所有线程都就位,门才打开,让所有线程一起通过。
构造方法
- 默认的构造方法是CyclicBarrier(int parties),其参数表示屏障拦截的线程数量,每个线程调用await方法告诉CyclicBarrier已经到达屏障位置,线程被阻塞。
- 另外一个构造方法CyclicBarrier(int parties, Runnable barrierAction),其中barrierAction任务会在所有线程到达屏障后执行。
应用场景
想象一个场景,运动会男子100米决赛,8名选手。
Athlete.java :每个运动员都就位后才开始。
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) {
}
}
}
Race.java : 负责屏障的初始化。
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);
}
}
}