// 内部调用dowait()方法,并且参数传false,不支持超时 public int await() throws InterruptedException, BrokenBarrierException { try { return dowait(false, 0L); } catch (TimeoutException toe) { throw new Error(toe); // cannot happen } }
// 真正进入等待的逻辑 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(); }
// 到达屏障的计数-1 int index = --count; if (index == 0) { // tripped // index == 0, 说明指定 count 的线程均到达屏障,此时可以打开屏障 boolean ranAction = false; try { final Runnable command = barrierCommand; if (command != null) // 若指定了 barrierCommand 则执行 command.run(); ranAction = true; // 唤醒阻塞在屏障的线程并重置 generation nextGeneration(); return 0; } finally { if (!ranAction) breakBarrier(); } }
// loop until tripped, broken, interrupted, or timed out 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 { // We're about to finish waiting even if we had not // been interrupted, so this interrupt is deemed to // "belong" to subsequent execution. Thread.currentThread().interrupt(); } }
// 屏障被破坏 则抛出异常 if (g.broken) throw new BrokenBarrierException();
if (g != generation) // g != generation 说明所有线程均到达屏障处 可直接返回 // 因为所有线程到达屏障处的时候,会重置 generation // 参考 nextGeneration return index;