//await方法的主要逻辑 privateintdowait(boolean timed, long nanos) throws InterruptedException, BrokenBarrierException, TimeoutException { //使用ReentrantLock final ReentrantLock lock = this.lock; //线程进来锁 lock.lock(); try { final Generation g = generation; //如果broken,抛异常 if (g.broken) thrownew BrokenBarrierException(); //线程中断,抛异常,唤醒Condition的等待线程 if (Thread.interrupted()) { breakBarrier(); thrownew InterruptedException(); }
//count自减 int index = --count; //如果自减至0,执行BarrierAction if (index == 0) { // tripped boolean ranAction = false; try { 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 { //非超时等待,直接调用condition的await方法,阻塞当前线程并释放锁 if (!timed) trip.await(); elseif (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(); } } //屏障被打破,线程从await方法返回,但是抛异常 if (g.broken) thrownew BrokenBarrierException(); //正常情况(Generation被重置),被唤醒后,返回index //什么情况下,Generation被重置? 1.BarrierAction执行 2.调用reset方法 if (g != generation) return index;
//重置Generation privatevoidnextGeneration(){ // signal completion of last generation trip.signalAll(); // set up next generation count = parties; generation = new Generation(); }