package concurrent;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Auth: zhouhongliang
* Date:2019/8/1
* 多个线同时运行
* CyclicBarrier
*/
public class CyclicBarrierDemo {
private static CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i=0;i<10;i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
executorService.execute(()->{
try {
play();
} catch (BrokenBarrierException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
public static void play() throws BrokenBarrierException, InterruptedException {
System.out.println(Thread.currentThread().getName() + " 已准备");
cyclicBarrier.await();
System.out.println(Thread.currentThread().getName() + " 开始执行");
}
}
输出结果:
pool-1-thread-1 已准备
pool-1-thread-2 已准备
pool-1-thread-3 已准备
pool-1-thread-4 已准备
pool-1-thread-5 已准备
pool-1-thread-5 开始执行
pool-1-thread-1 开始执行
pool-1-thread-2 开始执行
pool-1-thread-4 开始执行
pool-1-thread-3 开始执行
pool-1-thread-3 已准备
pool-1-thread-5 已准备
pool-1-thread-1 已准备
pool-1-thread-4 已准备
pool-1-thread-2 已准备
pool-1-thread-2 开始执行
pool-1-thread-1 开始执行
pool-1-thread-4 开始执行
pool-1-thread-5 开始执行
pool-1-thread-3 开始执行
Process finished with exit code 0