标签:
内容:一个主任务等待两个子任务,通过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); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/u011345136/article/details/46842183