场景1
public class MyTest02 {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
for(int i=0;i<3;i++){
new Thread(() -> {
try{
Thread.sleep((long)(Math.random() * 2000));
int randomInt = new Random().nextInt(500);
System.out.println("hello " + randomInt);
cyclicBarrier.await();
System.out.println("world " + randomInt);
}catch (Exception e){
e.printStackTrace();
}
}).start();
}
}
}
场景2
class Mytest03{
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(3,() -> {
System.out.println("冲破屏障,冲啊!!!");
});
for(int n=0;n<2;n++){
for (int j=0;j<3;j++){
new Thread(() -> {
try{
Thread.sleep((long)(Math.random() * 2000));
int randomInt = new Random().nextInt(500);
System.out.println("hello " + randomInt);
cyclicBarrier.await();
System.out.println("world " + randomInt);
}catch (Exception e){
e.printStackTrace();
}
}).start();
}
}
}
}
注意:
CountDownLatch的计数器归零后不会重置;而CyclicBarrier的计数器在每次多个线程冲破屏障后会重新恢复为初始值。