底层都是ReentrantLock,再底层实际上是CAS,AutomicXXX的一种体现形式
CountDownLatch是预先设一个值,然后减去,到0的时候await执行。
circle是预设一个目标值,到达目标值本身执行。
不多说直接案例:
运动大会:跑步比赛
运动员在入场就位过程中是CountDownLatch,待所有运动员就位,信号员信号枪装填弹药。
CyclicBarrier
裁判向所有运动员询问are you ready?
CyclicBarrier.await()全部准备完毕,同时起跑。
public static void prepare() throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(5);
for (int i = 0; i < 6; i++) {
new Thread(new Runnable() {
@Override
public void run() {
countDownLatch.countDown();
System.out.println(“运动员入参”+Thread.currentThread().getName() + " : " + countDownLatch.getCount());
}
}).start();
}
countDownLatch.await();
System.out.println("z装填弹药:"+Thread.currentThread().getName() + " : " + countDownLatch.getCount());
}
public static void run() {
CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
for (int i = 0; i < 5; i++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + " 就位"+cyclicBarrier.getParties());
cyclicBarrier.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (BrokenBarrierException e) {
throw new RuntimeException(e);
}
System.out.println(Thread.currentThread().getName() + " 开炮 " );
}
}).start();
}
System.out.println(Thread.currentThread().getName() + " 跑步开始 " + cyclicBarrier.getNumberWaiting());
}