CyclicBarrier:从字面上的意思可以知道,这个类的中文意思是“循环栅栏”。大概的意思就是一个可循环利用的屏障。一个线程组的线程需等到所有线程完成后才继续下一步。
例:
- CyclicBarrier(int parties):parties指定线程数
public static void main(String[] args) throws InterruptedException {
CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
cyclicBarrier(cyclicBarrier);
log.debug("main 1 thread end");
while (true) {
//cyclicBarrier未执行未执行await方法的线程数量,如上次未执行完毕执行reset方法则会抛出BrokenBarrierException异常
if (cyclicBarrier.getNumberWaiting() == 0){
//重置CyclicBarrier到新建状态
cyclicBarrier.reset();
cyclicBarrier(cyclicBarrier);
break;
}
}
log.debug("main thread end");
}
private static void cyclicBarrier(CyclicBarrier cyclicBarrier){
new Thread(() ->{
log.info(Thread.currentThread().getName() + " start "+System.currentTimeMillis());
try {
cyclicBarrier.await();
log.info(Thread.currentThread().getName() + " end "+System.currentTimeMillis());
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}, "threadA").start();
new Thread(() ->{
log.info(Thread.currentThread().getName() + " start "+System.currentTimeMillis());
try {
cyclicBarrier.await();
log.info(Thread.currentThread().getName() + " end "+System.currentTimeMillis());
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}, "threadB").start();
new Thread(() ->{
log.info(Thread.currentThread().getName() + " start "+System.currentTimeMillis());
try {
Thread.sleep(2000);
cyclicBarrier.await();
log.info(Thread.currentThread().getName() + " end "+System.currentTimeMillis());
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}, "threadC").start();
}
输出:
threadA start 1564562299025
threadB start 1564562299026
threadC start 1564562299027
main 1 thread end
threadC end 1564562301039
threadB end 1564562301039
threadA end 1564562301039
threadA start 1564562301039
threadB start 1564562301040
threadC start 1564562301040
main thread end
threadA end 1564562303043
threadB end 1564562303043
threadC end 1564562303043
CyclicBarrier与CountDownLatch的区别在于,CyclicBarrier执行reset方法后可以重复使用,需要注意的是:如果上一次所有线程没执行完成时,执行reset方法会抛出BrokenBarrierException异常。
- CyclicBarrier(int parties, Runnable barrierAction):barrierAction:最后一个线程执行了await后,会调用barrierAction。
public static void main(String[] args) throws InterruptedException {
CyclicBarrier cyclicBarrier = new CyclicBarrier(e,, ()->{
log.info("All Thread end");
});
cyclicBarrier(cyclicBarrier);
}
输出:
threadA start 1564562301039
threadB start 1564562301040
threadC start 1564562301040
main thread end
All Thread end
threadA end 1564562303043
threadB end 1564562303043
threadC end 1564562303043