CyclicbBarrier 的字面意思是可循环使用的屏障。它要做的事情是,让一组线程到达一个屏障(也可以叫同步点)时被阻塞,直到最后一个线程到达屏障时,屏障才会开门,所有被屏障拦截的线程才会继续运行
循环栅栏,用来进行线程协作,等待线程满足某个计数。构造时设置『计数个数』,每个线程执
行到某个需要“同步”的时刻调用 await() 方法进行等待,当等待的线程数满足『计数个数』时,继续执行
public class TestCyclicBarrier {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
CyclicBarrier barrier = new CyclicBarrier(2,() -> {
System.out.println("[" + Thread.currentThread().getName() + "]" + "task1and2 finish.....");
});
for (int i = 0; i < 3; i++) {
pool.submit(() -> {
System.out.println("[" + Thread.currentThread().getName() + "]" + "task1 begin.....");
try {
Thread.sleep(1000);
barrier.await();//2-1=1
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
});
pool.submit(() -> {
System.out.println("[" + Thread.currentThread().getName() + "]" + "task2 begin.....");
try {
Thread.sleep(2000);
barrier.await();//1-1=0
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
});
}
pool.shutdown();
}
}
[pool-1-thread-1]task1 begin.....
[pool-1-thread-2]task2 begin.....
[pool-1-thread-2]task1and2 finish.....
[pool-1-thread-1]task1 begin.....
[pool-1-thread-2]task2 begin.....
[pool-1-thread-2]task1and2 finish.....
[pool-1-thread-2]task1 begin.....
[pool-1-thread-1]task2 begin.....
[pool-1-thread-1]task1and2 finish.....
注意
CyclicBarrier 与 CountDownLatch 的主要区别在于 CyclicBarrier 是可以重用的
CyclicBarrier 可以被比喻为『人满发车』