privateintdowait(boolean timed, long nanos) throws InterruptedException, BrokenBarrierException, TimeoutException { // 利用可重入锁,保证同时只有一个线程能进入 final ReentrantLock lock = this.lock; lock.lock(); try { final Generation g = generation;
if (g.broken) thrownew BrokenBarrierException();
if (Thread.interrupted()) { breakBarrier(); thrownew InterruptedException(); }
// 每次调用该方法,count自减 int index = --count; // 等于0时,表示所有线程都已到达屏障 if (index == 0) { // tripped boolean ranAction = false; try { // 如果构造函数有传入command,就执行 final Runnable command = barrierCommand; if (command != null) command.run(); ranAction = true; // 唤醒所有等待线程,并重置 nextGeneration(); return0; } finally { if (!ranAction) breakBarrier(); } }
// loop until tripped, broken, interrupted, or timed out // 所有线程没有全部到达屏障时 for (;;) { try { // 如果未设置超时,调用Contion.await(),将线程放入等待队列 if (!timed) trip.await(); // elseif (nanos > 0L) // 如果设置了超时,调用Contion.awaitNanos(nanos),将线程放入等待队列 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(); } }