CyclicBarrier是一个同步工具类, 它允许一组线程互相等待, 直到到达某个公共屏障点, 与CountDownLatch不同的是该barrier在释放等待线程后可以重用, 所以称它为循环(Cyclic)的屏障(Barrier)
–只有4个线程全都就绪了, 才开始运行
–示例代码
package com.ygq.thread.threadPool;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author :GQ.Yin
* @date :Created in 2019/7/22 14:52
* @description:CyclicBarrier循环屏障
* @version: $version$
*/
public class CyclicBarrierSample {
//首先定义一个屏障点, 同时必须有5个线程就绪, 才可以运行
private static CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {
final int index = i;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
executorService.execute(new Runnable() {
public void run() {
go();
}
});
}
executorService.shutdown();
}
private static void go(){
System.out.println(Thread.currentThread().getName() + " 准备就绪");
try {
cyclicBarrier.await(); //设置屏障点, 当累计 5 个线程都准备好 才运行后面的 代码
System.out.println(Thread.currentThread().getName() + " 开始运行了");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}