一、介绍 让一组线程到达一个屏障(也可以叫同步点)时被阻塞,直到最后一个线程到达屏障
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 private static CyclicBarrier c=new CyclicBarrier (); public static void main (String[] args) { new Thread (new Runnable () { @Override public void run () { try { c.await(); } catch (Exception e) { } System.out.println(1 ); } }).start(); try { c.await(); } catch (Exception e) { } System.out.println(2 ); }
二、源码分析 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 public class CyclicBarrier { private final ReentrantLock lock = new ReentrantLock (); private final Condition trip = lock.newCondition(); private int dowait (boolean timed, long nanos) throws InterruptedException, BrokenBarrierException, TimeoutException { final ReentrantLock lock = this .lock; lock.lock(); try { final Generation g = generation; if (g.broken) throw new BrokenBarrierException (); if (Thread.interrupted()) { breakBarrier(); throw new InterruptedException (); } int index = --count; if (index == 0 ) { boolean ranAction = false ; try { final Runnable command = barrierCommand; if (command != null ) command.run(); ranAction = true ; nextGeneration(); return 0 ; } finally { if (!ranAction) breakBarrier(); } } for (;;) { try { if (!timed) trip.await(); else if (nanos > 0L ) nanos = trip.awaitNanos(nanos); } catch (InterruptedException ie) { if (g == generation && ! g.broken) { breakBarrier(); throw ie; } else { Thread.currentThread().interrupt(); } } if (g.broken) throw new BrokenBarrierException (); if (g != generation) return index; if (timed && nanos <= 0L ) { breakBarrier(); throw new TimeoutException (); } } } finally { lock.unlock(); } } public int await () throws InterruptedException, BrokenBarrierException { try { return dowait(false , 0L ); } catch (TimeoutException toe) { throw new Error (toe); } } private void breakBarrier () { generation.broken = true ; count = parties; trip.signalAll(); } private void nextGeneration () { trip.signalAll(); count = parties; generation = new Generation (); } }
从代码中可以看出CyclicBarrier和CountDownLatch的区别:
CountDownLatch是通过共享锁机制实现的计数阻塞
CyclicBarrier使用的是Condition实现的计数阻塞,CyclicBarrier是自己维护了一个count,当count=0时,唤醒所有的条件队列中的节点,然后重置count的数量。