并发包下常见的同步工具类详解(CountDownLatch,CyclicBarrier,Semaphore) (2)

同步状态依旧使用AQS中的state值进行表示,在CountDownLatch的语境下表示计数器的值,且只有在state=0时线程才能成功获取到同步状态,尽管有些奇怪,不过考虑到CountDownLatch中的计数器是个倒计数器,这么设定也并非不可理解。为了更好的理解CountDownLatch的源码,从释放同步状态的方法countDown()开始讲起

public void countDown() { sync.releaseShared(1); }

正确找到sync的实现类后跟进源码

public final boolean releaseShared(int arg) { if (tryReleaseShared(arg)) { //尝试在共享模式下释放同步状态 doReleaseShared(); return true; } return false; }

tryReleaseShared()尝试在共享模式下释放同步状态,该方法是在AQS中定义的钩子方法,必须由AQS的实现类自己实现,方法内容如下

protected boolean tryReleaseShared(int releases) { // Decrement count; signal when transition to zero for (;;) { int c = getState(); //获取同步状态值 if (c == 0) return false; int nextc = c-1; if (compareAndSetState(c, nextc)) //以CAS方式更新同步状态值 return nextc == 0; } }

使用死循环+CAS方式将计数值state减少1。仅当更新操作成功且state值被更新为0时返回true,表示在共享模式下释放同步状态成功,接着便会继续执行doReleaseShared()方法,方法内容如下

private void doReleaseShared() { /* * Ensure that a release propagates, even if there are other * in-progress acquires/releases. This proceeds in the usual * way of trying to unparkSuccessor of head if it needs * signal. But if it does not, status is set to PROPAGATE to * ensure that upon release, propagation continues. * Additionally, we must loop in case a new node is added * while we are doing this. Also, unlike other uses of * unparkSuccessor, we need to know if CAS to reset status * fails, if so rechecking. */ for (;;) { Node h = head; if (h != null && h != tail) { int ws = h.waitStatus; if (ws == Node.SIGNAL) { if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0)) continue; // loop to recheck cases unparkSuccessor(h); //唤醒后继结点中的线程 } else if (ws == 0 && !compareAndSetWaitStatus(h, 0, Node.PROPAGATE)) continue; // loop on failed CAS } if (h == head) // loop if head changed break; } }

该方法主要完成的工作是唤醒头结点之后的结点中的线程。那么其他在同步队列中等待的线程使如何被唤醒的?别急,我们可以在await()方法中找到答案。

public void await() throws InterruptedException { sync.acquireSharedInterruptibly(1); }

找到sync正确的实现类后跟进源码

public final void acquireSharedInterruptibly(int arg) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); if (tryAcquireShared(arg) < 0) doAcquireSharedInterruptibly(arg); }

tryAcquireShared()是在共享模式下尝试获取同步状态,

protected int tryAcquireShared(int acquires) { return (getState() == 0) ? 1 : -1; }

当同步状态值state=0时返回1,表示获取同步状态成功,否则返回-1表示获取同步状态失败。获取同步状态失败的线程显然应该加入同步等待队列并在队列中等待,这部分逻辑我们在解读ReentrentLock的源码时应该已经看过了,不过在共享模式下细节方面有些不同

/** * Acquires in shared interruptible mode. * @param arg the acquire argument */ private void doAcquireSharedInterruptibly(int arg) throws InterruptedException { final Node node = addWaiter(Node.SHARED);//构造结点并加入同步队列 boolean failed = true; try { for (;;) { final Node p = node.predecessor(); if (p == head) { int r = tryAcquireShared(arg);//当前驱结点是头结点时获取同步状态 if (r >= 0) { setHeadAndPropagate(node, r); p.next = null; // help GC failed = false; return; } } if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) throw new InterruptedException(); } } finally { if (failed) cancelAcquire(node); } }

第一步自然是构造结点并加入同步队列尾部,这部分逻辑在addWaiter()方法中,注意结点类型为共享类型。之后的逻辑和独占模式类似,检查前驱结点是否是队列的头结点,是则尝试获取同步状态,成功则将当前结点设置为队列头结点,失败则阻塞当前线程并等待唤醒并重新执行以上流程。不过在共享模式下,当前线程在成功获取同步状态并设置自身为头结点后,还必须做些额外的工作:当后继结点为共享类型时,唤醒后继结点中的线程。

private void setHeadAndPropagate(Node node, int propagate) { Node h = head; // Record old head for check below setHead(node); //设置当前结点为队列头结点 /* * Try to signal next queued node if: * Propagation was indicated by caller, * or was recorded (as h.waitStatus either before * or after setHead) by a previous operation * (note: this uses sign-check of waitStatus because * PROPAGATE status may transition to SIGNAL.) * and * The next node is waiting in shared mode, * or we don't know, because it appears null * * The conservatism in both of these checks may cause * unnecessary wake-ups, but only when there are multiple * racing acquires/releases, so most need signals now or soon * anyway. */ if (propagate > 0 || h == null || h.waitStatus < 0 || (h = head) == null || h.waitStatus < 0) { Node s = node.next; if (s == null || s.isShared()) doReleaseShared(); //唤醒后继结点的线程 } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyzypg.html