两者的区别
- CountDownLatch 主要用来解决一个线程等待多个线程的场景
- CyclicBarrier 是一组线程之间互相等待
CountDownLatch
- 构造方法
- 使用demo
public static void main(String[] args) throws InterruptedException {
//创建一个 countDownLatch
CountDownLatch countDownLatch = new CountDownLatch(2);
new Thread(()->{
//计数器减一
countDownLatch.countDown();
}, "线程一").start();
new Thread(()->{
//计数器减一
countDownLatch.countDown();
}, "线程二").start();
//阻塞当前的main线程等待 countDownLatch 计数器为0 被唤醒
countDownLatch.await();
System.out.println("main线程 等到 线程一 线程二 执行完 countDownLatch.countDown() 计数器为0 main线程被唤醒");
}
CyclicBarrier
-
两种构造方法
-
使用demo
public static void main(String[] args) throws InterruptedException {
CyclicBarrier barrier = new CyclicBarrier(3);
new Thread(()->{
try {
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
},"线程一");
new Thread(()->{
try {
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
},"线程二");
new Thread(()->{
try {
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
},"线程三");
System.out.println("每个线程调用到barrier.await() 会进入到等待状态,当三个线程都调用了 barrier.await(), 计数器累加 到3 突破了屏障 同步执行");
}