/** The lock for guarding barrier entry ,守护入口的锁*/ privatefinalReentrantLocklock=newReentrantLock(); /** Condition to wait on until tripped,等待条件 */ privatefinalConditiontrip= lock.newCondition(); /** The number of parties,要屏障的线程数 */ privatefinalint parties; /* The command to run when tripped ,当线程都到待barrier,需要运行的内容*/ privatefinal Runnable barrierCommand; /** The current generation ,记录当前barrier状态的对象*/ privateGenerationgeneration=newGeneration();
/** * Number of parties still waiting. Counts down from parties to 0 * on each generation. It is reset to parties on each new * generation or when broken. *当前等待barrier到达的线程的数量 */ privateint count;
// loop until tripped, broken, interrupted, or timed out //自旋等待,直到所有线程都到达屏障点 //或者发生中断 //或者generation被销毁 //或者超时 for (;;) { try { if (!timed) trip.await(); //在此利用lock的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(); } }
privatevoidnextGeneration() { // signal completion of last generation trip.signalAll(); //唤醒所有的等待线程 // set up next generation count = parties;//将等待线程数复原,以便CyclicBarrier下次重复使用 generation = newGeneration(); //复原generation }