阻塞等待的核心方法,内部会调用trip.await()方法进入Condition等待阻塞队列,一旦栅栏数量为零时则会逐个逐个将Condition等待的队列转移到CLH的等待阻塞队列;
所有线程被唤醒后然后等待dowait方法内部lock.unlock()一个个释放线程等待,阻塞的最后一个线程还有机会执行构造方法传入的接口回调;
/** * Waits until all {@linkplain #getParties parties} have invoked * {@code await} on this barrier. * * <p>If the current thread is not the last to arrive then it is * disabled for thread scheduling purposes and lies dormant until * one of the following things happens: * <ul> * <li>The last thread arrives; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} * one of the other waiting threads; or * <li>Some other thread times out while waiting for barrier; or * <li>Some other thread invokes {@link #reset} on this barrier. * </ul> * * <p>If the current thread: * <ul> * <li>has its interrupted status set on entry to this method; or * <li>is {@linkplain Thread#interrupt interrupted} while waiting * </ul> * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. * * <p>If the barrier is {@link #reset} while any thread is waiting, * or if the barrier {@linkplain #isBroken is broken} when * {@code await} is invoked, or while any thread is waiting, then * {@link BrokenBarrierException} is thrown. * * <p>If any thread is {@linkplain Thread#interrupt interrupted} while waiting, * then all other waiting threads will throw * {@link BrokenBarrierException} and the barrier is placed in the broken * state. * * <p>If the current thread is the last thread to arrive, and a * non-null barrier action was supplied in the constructor, then the * current thread runs the action before allowing the other threads to * continue. * If an exception occurs during the barrier action then that exception * will be propagated in the current thread and the barrier is placed in * the broken state. * * @return the arrival index of the current thread, where index * {@code getParties() - 1} indicates the first * to arrive and zero indicates the last to arrive * @throws InterruptedException if the current thread was interrupted * while waiting * @throws BrokenBarrierException if <em>another</em> thread was * interrupted or timed out while the current thread was * waiting, or the barrier was reset, or the barrier was * broken when {@code await} was called, or the barrier * action (if present) failed due to an exception */ public int await() throws InterruptedException, BrokenBarrierException { try { return dowait(false, 0L); // 阻塞的核心方法,重心再次,通过ReentrantLock和Condition组合完成阻塞等待 } catch (TimeoutException toe) { throw new Error(toe); // cannot happen } }dowait(false, 0L); // 阻塞的核心方法,重新再次,通过ReentrantLock和Condition组合完成阻塞等待
3.3、dowait(boolean, long)dowait方法是CyclicBarrier实现阻塞等待的核心方法,当await方法被调用时阻塞等待被Condition的一个队列维护着;
然而线程从await跳出来时,正常情况下一般都是由于发送了信号量,阻塞被解除,那么Condition的等待队列将会被转移至AQS的等待队列;
然后一个逐渐锁释放,最后CyclicBarrier也处于了初始值状态,供下次调用使用;
因此CyclicBarrier每用完一套整个流程,又会回到初始状态值,又可以被其他地方当做新创建的对象一样来使用,所以才成为循环栅栏;
/** * Main barrier code, covering the various policies. */ private int dowait(boolean timed, long nanos) throws InterruptedException, BrokenBarrierException, TimeoutException { final ReentrantLock lock = this.lock; // 获取独占锁 lock.lock(); // 通过lock其父类AQS的CLH队列阻塞在此,但是为啥又会继续往下进入临界区执行try方法,其原因就是trip.await()这句代码 try { final Generation g = generation; if (g.broken) // 若平衡被一旦打破,则其他所有的线程都会抛出异常,因为即使这里没遇到抛异常,下面还会有 if (g.broken) 判断 throw new BrokenBarrierException(); if (Thread.interrupted()) { // 检测线程是否在其他地方被中断过,若任何一个线程被中断过 breakBarrier(); // 那么则打破平衡,并设置打破平衡的标志,还原初始状态值,然后再唤醒所有被阻塞的线程, throw new InterruptedException(); } int index = --count; // 执行一个则减1操作,正常情况下count表示还有多少个未进入临界区,即还在lock阻塞队列中 if (index == 0) { // tripped 当count值降为0后,则表明所有线程都执行完了,那么就可以happy的一起改朝换代去做其他事情了 boolean ranAction = false; try { final Runnable command = barrierCommand; // 构造方法传入的接口回调对象 if (command != null) // 当接口不为空时,最后一个执行的线程有机会消费该回调方法 command.run(); ranAction = true; nextGeneration(); // 改朝换代,该执行的都已经执行完了,还原为初始状态值,以便下次可以重复再次使用 return 0; } finally { if (!ranAction) // 若最后一个线程眼看着要完事了,若出现了任何异常的话,也照样打破整体平衡,要么一起生要么一起亡 breakBarrier(); } } // loop until tripped, broken, interrupted, or timed out for (;;) { // 自旋的死循环操作方式 try { if (!timed) // 若不需要使用超时等待信号量的话,那么下面就直接调用trip.await()进入阻塞等待 trip.await(); // 正常情况下,代码执行到此就不动了,该方法内部已经调用了park方法导致线程阻塞等待 else if (nanos > 0L) nanos = trip.awaitNanos(nanos); // 在指定时间内等待信号量 } catch (InterruptedException ie) { // 若在阻塞等待期间由于被中断了 if (g == generation && ! g.broken) { // 如果还没改朝换代,并且平衡标志位还为false的话,则继续打破平衡并且抛出中断异常 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) // 这里也有 if (g.broken) 判断,若平衡被一旦打破,则其他所有的线程都会抛出异常 throw new BrokenBarrierException(); if (g != generation) // 若已经被改朝换代了,那么则直接返回index值 return index; if (timed && nanos <= 0L) { // 若设置了超时标志,并且不管是传入的nanos值也好还是通过等待后返回的nanos也好,只要小于或等于零都会打破平衡 breakBarrier(); throw new TimeoutException(); } } } finally { lock.unlock(); // 释放lock锁 } } breakBarrier()