package com.han.demo01;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CB {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {//一旦7个线程的任务执行完,这个事件立即触发
System.out.println("触发事件!");
});
for (int i = 1; i <= 7; i++) {
int temp = i;//事实最终变量
new Thread(() -> {
System.out.println("做第" + temp + "件事");
try {
cyclicBarrier.await();//阻塞
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
结果: