CyclicBarrier(循环栅栏)
CyclicBarrier可以使一定数量的参与方反复地在栅栏位置汇集
CyclicBarrier初始化的时候,设置一个屏障数。线程调用await()方法的时候,这个线程就会被阻塞,当调用await()的线程数量到达屏障数的时候,主线程就会取消所有被阻塞线程的状态
示例
/**
* 三个人一起爬山,达到第一集合点后必须等到所有人员到齐后再开始往第二集合点进发
*/
public class Appliction {
private static final int NUM = 3;
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(NUM);
String phaseName = "phase one";
for (int i = 0; i < NUM; i++) {
new Thread(new PhaseTask(phaseName, cyclicBarrier)).start();
}
}
}
class PhaseTask implements Runnable {
private String phaseName;
private CyclicBarrier cyclicBarrier;
public PhaseTask(String phaseName, CyclicBarrier cyclicBarrier) {
this.phaseName = phaseName;
this.cyclicBarrier = cyclicBarrier;
}
@Override
public void run() {
sleep();
System.err.println(Thread.currentThread().getName() + "到达第一个集合点");
waitFor();
sleep();
System.err.println(Thread.currentThread().getName() + "到达第二个集合点");
waitFor();
}
private void sleep() {
int time = new Random().nextInt(10);
if (time > 0) {
try {
TimeUnit.SECONDS.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void waitFor() {
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}