package jTest; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.Phaser; public class ConcurrentToolsExample { public static void main(String[] args) throws InterruptedException, BrokenBarrierException { CyclicBarrier cyclicBarrier = new CyclicBarrier(2); CountDownLatch countDownLatch = new CountDownLatch(1); Phaser phaser = new Phaser(1); // 初始注册线程数为1 new Thread(() -> { try { cyclicBarrier.await(); // 等待 // 执行任务 } catch (Exception e) { e.printStackTrace(); } }).start(); new Thread(() -> { try { countDownLatch.await(); // 等待 // 执行任务 } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }).start(); // 到达并等待 // 执行任务 new Thread(phaser::arriveAndAwaitAdvance).start(); // 模拟一些前置操作 Thread.sleep(1000); countDownLatch.countDown(); // 计数减一,允许等待的线程继续执行 cyclicBarrier.await(); // 释放等待的线程 phaser.register(); // 增加一个参与者 } }