功能描述
CyclicBarrier(回环栅栏或循环屏障),是Java并发库中的一个同步工具,通过它可以实现让一组线程等待至某个状态(屏障点)之后再全部同时执行。叫做回环是因为当所有等待线程都被释放以后,CyclicBarrier可以被重用。与CountDownLatch的区别是CyclicBarrier是可以循环使用的。CyclicBarrier使用ReentrantLock+Condition实现。
API
- await() 每个线程调用await方法告诉CyclicBarrier我已经到达了屏障,然后当前线程被阻塞。所有的线程全部调用await()方法时,这些线程不再阻塞
- await(long timeout, TimeUnit unit)
使用示例
public class Main {
public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
final CyclicBarrier barrier = new CyclicBarrier(11);
for(int i = 0; i < 10; i++) {
new Thread(new Tourist(i, barrier)).start();
}
barrier.await();
System.out.println("所有人都上了车");
barrier.await();
System.out.println("所有人都下了车");
}
private static class Tourist implements Runnable {
private final int touristID;
private final CyclicBarrier barrier;
public Tourist(int id, CyclicBarrier barrier) {
this.touristID = id;
this.barrier = barrier;
}
@Override
public void run() {
System.out.printf("游客%d乘坐旅游大巴\n", touristID);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
try {
System.out.printf("游客%d上车,等别人上车\n", touristID);
barrier.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (BrokenBarrierException e) {
throw new RuntimeException(e);
}
System.out.printf("游客%d到达目的地\n", touristID);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
try {
System.out.printf("游客%d下车,等别人下车\n", touristID);
barrier.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (BrokenBarrierException e) {
throw new RuntimeException(e);
}
}
}
}