内容:一个主任务等待两个子任务,通过CyclicBarrier的await()实现。此Runnable任务在CyclicBarrier的数目达到后,全部其他线程被唤醒前被运行。
public class CyclicBarrierTest { class MainTask implements Runnable { @Override public void run() { System.out.println(">>>>主任务開始运行!<<<<"); } } class SubTask implements Runnable { private String name; private CyclicBarrier cyclicBarrier; SubTask(String name, CyclicBarrier cyclicBarrier) { this.name = name; this.cyclicBarrier = cyclicBarrier; } @Override public void run() { System.out.println("[子任务" + name + "]開始运行了!"); for (int i = 0; i < 999999; i++) ; System.out.println("[子任务" + name + "]运行完毕了,并通知障碍器已经完毕了"); try { cyclicBarrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } } } public static void main(String[] args) { CyclicBarrierTest test = new CyclicBarrierTest(); CyclicBarrier cyclicBarrier = new CyclicBarrier(2, test.new MainTask()); SubTask A = test.new SubTask("A", cyclicBarrier); SubTask B = test.new SubTask("B", cyclicBarrier); ExecutorService executor = Executors.newCachedThreadPool(); executor.execute(A); executor.execute(B); } }