CyclicBarrier
CyclicBarrier叫做回环屏障,它的作⽤是让⼀组线程全部达到⼀个状态之后再全部同时执⾏,⽽且它有⼀个特点就是所有线程执⾏完毕之后是可以重⽤的。
public class CyclicBarrierTest { private static int num = 3; private static CyclicBarrier cyclicBarrier = new CyclicBarrier(num, () -> { System.out.println("所有⼈都好了,开始开会..."); System.out.println("-------------------"); }); private static ExecutorService executorService = Executors.newFixedThreadPool(num); public static void main(String[] args) throws Exception { executorService.submit(() -> { System.out.println("A在上厕所"); try { Thread.sleep(4000); System.out.println("A上完了"); cyclicBarrier.await(); System.out.println("会议结束,A退出"); } catch (Exception e) { e.printStackTrace(); } finally { } }); executorService.submit(() -> { System.out.println("B在上厕所"); try { Thread.sleep(2000); System.out.println("B上完了"); cyclicBarrier.await(); System.out.println("会议结束,B退出"); } catch (Exception e) { e.printStackTrace(); } finally { } }); executorService.submit(() -> { System.out.println("C在上厕所"); try { Thread.sleep(3000); System.out.println("C上完了"); cyclicBarrier.await(); System.out.println("会议结束,C退出"); } catch (Exception e) { e.printStackTrace(); } finally { } }); executorService.shutdown(); }}
从结果来看和CountDownLatch⾮常相似,初始化传⼊3个线程和⼀个任务,线程调⽤await()之后进⼊阻塞,计数器-1,当计数器为0时,就去执⾏CyclicBarrier中构造函数的任务,当任务执⾏完毕后,唤醒所有阻塞中的线程。这验证了CyclicBarrier让⼀组线程全部达到⼀个状态之后再全部同时执⾏的效果。
测试结果