/** The lock for guarding barrier entry */ //是之前提及的可重用锁 privatefinal ReentrantLock lock = new ReentrantLock(); /** Condition to wait on until tripped */ //Condition即java分配给每个对象的monitor相关数据结构,有notify notifyAll wait等方法 privatefinal Condition trip = lock.newCondition(); /** The number of parties */ privatefinalint parties; /* The command to run when tripped */ privatefinal Runnable barrierCommand; /** The current generation */ private Generation generation = new Generation(); //... /** * Updates state on barrier trip and wakes up everyone. * Called only while holding lock. */ privatevoidnextGeneration(){ // signal completion of last generation trip.signalAll();//condition中的方法,把所有线程都唤醒 // set up next generation count = parties; generation = new Generation(); } /** * Sets current barrier generation as broken and wakes up everyone. * Called only while holding lock. */ privatevoidbreakBarrier(){ generation.broken = true; count = parties; trip.signalAll(); } publicintawait()throws InterruptedException, BrokenBarrierException { try { return dowait(false, 0L); } catch (TimeoutException toe) { thrownew Error(toe); // cannot happen } } //可能抛出中断、超时 阻塞中断异常 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(); }
int index = --count;//记录有线程到达目的地 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 { if (!timed) trip.await();//condition的方法 让当前线程等待 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();//如果出现意外上面的条件没执行 也要主动打断 } }