java并发编程学习之再谈CountDownLatch

5次阅读

共计 2461 个字符,预计需要花费 7 分钟才能阅读完成。

之前讲了 AQS 的独占锁的源码,这边,讲一下另外一个锁的实现,共享锁,以 CountDownLatch 为例。

源码分析

构造方法

Sync 方法是内部内的方法,跟之前 ReentrantLock 一样。构造方法需要传入一个不小于 0 的整数,用于赋值给 state。当其他线程调用 countDown 方法的时候,state 的值就减一。减到 0 的时候,其他调用 await 方法将被唤醒。await 方法可以被多个线程调用,调用的时候,就进入了阻塞状态,直至 state 为 0。后面重点讲 countDown 和 await 方法。

public CountDownLatch(int count) {if (count < 0) throw new IllegalArgumentException("count < 0");
    this.sync = new Sync(count);
}
Sync(int count) {setState(count);
}

await

我们先看看阻塞的方法,此时要等 state 为 0 的时候,才被唤醒。

public void await() throws InterruptedException {sync.acquireSharedInterruptibly(1);
}
public final void acquireSharedInterruptibly(int arg)
            throws InterruptedException {if (Thread.interrupted())// 中断情况,抛出异常
        throw new InterruptedException();
    if (tryAcquireShared(arg) < 0)
        doAcquireSharedInterruptibly(arg);//state 不为 0 的情况下
}
protected int tryAcquireShared(int acquires) {return (getState() == 0) ? 1 : -1;// 当前状态为 0,返回 1
}
private void doAcquireSharedInterruptibly(int arg)// 获取共享锁,并且可被中断
    throws InterruptedException {final Node node = addWaiter(Node.SHARED);// 这个跟之前不同的是 Node.SHARED,加入到队列,不在说明
    boolean failed = true;
    try {for (;;) {// 自旋
            final Node p = node.predecessor();// 获取前面节点
            if (p == head) {int r = tryAcquireShared(arg);// 尝试获取锁
                if (r >= 0) {//state 为 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);
    }
}

countDown

public void countDown() {sync.releaseShared(1);
}
public final boolean releaseShared(int arg) {if (tryReleaseShared(arg)) {doReleaseShared();// 为 true,唤醒
        return true;
    }
    return false;
}
// 用自旋使 status-1
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))
            return nextc == 0;
    }
}
private void doReleaseShared() {for (;;) {
        Node h = head;
        if (h != null && h != tail) {// 有阻塞队列,并且头节点不是尾节点
            int ws = h.waitStatus;
            if (ws == Node.SIGNAL) {if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))// 通过 cas 把头节点的 waitStatus 设置为 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;//
    }
}

刚刚 wait 的时候,doAcquireSharedInterruptibly 中如果没获取到锁,就挂起。现在 status 为 0,就唤醒他,继续自旋,次数看下面的代码

private void setHeadAndPropagate(Node node, int propagate) {
    Node h = head; // Record old head for check below 获取头结点
    setHead(node);// 当前节点设置为头节点
    
    if (propagate > 0 || h == null || h.waitStatus < 0 ||
        (h = head) == null || h.waitStatus < 0) {
        Node s = node.next;// 获取下一个节点
        if (s == null || s.isShared())
            doReleaseShared();// 唤醒下一个节点}
}

正文完
 0