概述
CyclicBarrier:栅栏的概念,多线程的进行阻塞,等待某一个临界值条件满足后,同时执行!
场景:每个线程代表一个跑步运动员,当运动员都准备好后,才一起出发,只要有一个人没有准备好,大家都等待!
public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
CyclicBarrier cyclicBarrier = new CyclicBarrier(4);
ExecutorService executorService = Executors.newFixedThreadPool(4);
for (int i = 0; i < 4; i++) {
int finalI = i;
executorService.execute(() -> {
try {
Thread.sleep(1000 * (new Random()).nextInt(5));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.err.println("运动员" + finalI + "准备就绪");
try {
cyclicBarrier.await(); //每个线程都调用await()后,所有线程开始执行
System.err.println("运动员" + finalI + "开始跑");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
});
}
executorService.shutdown();
}