java.util.concurrent.CyclicBarrier Dear 丶 2022-06-06 10:53 152阅读 0赞 ## java.util.concurrent.CyclicBarrier ## ### 概述 ### CyclicBarrier可以看作是一个栅栏队列。即一组相互联系的并行的任务在进入下一个业务场景时需要同时完成各自的任务,如果其中一个任务未完成,其它任务均需要等待未完成任务执行完毕后,一起进入下一下场景。 ### 应用场景 ### ### CyclicBarrier与CountDownLatch的区别 ### * CountDownLatch的计数器只能被初始化一次,CyclicBarrier的计数器可以使用reset()方法进行重置。 * CyclicBarrier还提供了其它有用的方法。如:getNumberWaiting()获取当前被阻塞线程的数量 ### 代码示例 ### public class CyclicBarrierDemo { static class Runner implements Runnable { private CyclicBarrier cyclicBarrier; private String name; public Runner (CyclicBarrier cyclicBarrier, String name) { this.cyclicBarrier = cyclicBarrier; this.name = name; } @Override public void run() { try { Thread.sleep(1000 * (new Random()).nextInt(5)); System.out.println(name + "-准备ok!"); /** * 阻塞当前线程,直到被阻塞线程的数量等于CyclicBarrier对象的初始计数值时开始继续执行后续的程序 */ cyclicBarrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } System.out.println(name + " Let's go!!!"); } } public static void main(String[] args) { /** * 初始化一个栅栏数为3的CyclicBarrier对象 * 意味着当前有3个任务需要同时完成后再进入一下任务 */ CyclicBarrier cyclicBarrier = new CyclicBarrier(3); /** * 初始化一个数量为3的线程池,并分别实例化三个线程 */ ExecutorService executorService = Executors.newFixedThreadPool(3); executorService.submit(new Thread(new Runner(cyclicBarrier, "zhangsan"))); executorService.submit(new Thread(new Runner(cyclicBarrier, "lisi"))); executorService.submit(new Thread(new Runner(cyclicBarrier, "wangwu"))); executorService.shutdown(); } } 源代码链接:[https://github.com/myNameIssls/javase-study/blob/master/javase-multithreading/src/main/java/cn/tyrone/javase/concurrent/CyclicBarrierDemo.java][https_github.com_myNameIssls_javase-study_blob_master_javase-multithreading_src_main_java_cn_tyrone_javase_concurrent_CyclicBarrierDemo.java] 参考链接:[http://ifeve.com/concurrency-cyclicbarrier/][http_ifeve.com_concurrency-cyclicbarrier] [https_github.com_myNameIssls_javase-study_blob_master_javase-multithreading_src_main_java_cn_tyrone_javase_concurrent_CyclicBarrierDemo.java]: https://github.com/myNameIssls/javase-study/blob/master/javase-multithreading/src/main/java/cn/tyrone/javase/concurrent/CyclicBarrierDemo.java [http_ifeve.com_concurrency-cyclicbarrier]: http://ifeve.com/concurrency-cyclicbarrier/
还没有评论,来说两句吧...