CyclicBarrier用于阻塞多个已经启动的线程先后到达某个条件的时候,同时执行后续的操作。
public class CyclicBarrierTest {
public static void main(String[] args) throws InterruptedException {
new CyclicBarrierTest().go();
}
private void go() throws InterruptedException {
// 初始化栅栏的参与者数为3
CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
// 依次创建3个线程,并启动
new Thread(new Task(cyclicBarrier), "Thread1").start();
Thread.sleep(1000);
new Thread(new Task(cyclicBarrier), "Thread2").start();
Thread.sleep(1000);
new Thread(new Task(cyclicBarrier), "Thread3").start();
}
class Task implements Runnable {
private CyclicBarrier cyclicBarrier;
public Task(CyclicBarrier cyclicBarrier) {
this.cyclicBarrier = cyclicBarrier;
}
@Override
public void run() {
System.out.println("线程" + Thread.currentThread().getName() + "已经到达" + System.currentTimeMillis());
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println("线程" + Thread.currentThread().getName() + "开始处理" + System.currentTimeMillis());
}
}
}
输出:
线程Thread1已经到达1488868149950
线程Thread2已经到达1488868150951
线程Thread3已经到达1488868151956
线程Thread3开始处理1488868151956
线程Thread1开始处理1488868151956
线程Thread2开始处理1488868151956
可见,线程1、2、3先后到达,到达的时间点为:1488868151956。在线程Thread3到达后,同时(1488868151956)执行各自的后续操作。