JUC.CountDownLatch

38 阅读1分钟

JUC.CountDownLatch

运行一下

public class CountDownLatchDemo {
    private static int N = 10;
    private static volatile Integer current = 0;

    public static void main(String[] args){
        CountDownLatch doneSignal = new CountDownLatch(N);
        Executor e = Executors.newFixedThreadPool(N / 2);
        for (int i = 0; i < N; ++i) {
            // create and start threads
            e.execute(() -> {
                current++;
                doneSignal.countDown();
            });
        }

        try {
            doneSignal.await();
        } catch (InterruptedException ex) {
            throw new RuntimeException(ex);
        }
        System.out.println("current: " + current);
        // wait for all to finish
    }
}

核心部分

1.初始化计数

CountDownLatch doneSignal = new CountDownLatch(N);

2.线程内部进行计数扣减

doneSignal.countDown();

3.等待计数器完成

doneSignal.await();

实现原理

1.通过state维护计数

2.共享锁,所有线程都可以进行更改state

3.为0则计数完成

计数初始化

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

计数减

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

执行释放锁

public final boolean releaseShared(int arg) {
    if (tryReleaseShared(arg)) {
        doReleaseShared();
        return true;
    }
    return false;
}

尝试释放锁

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))
                    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;
    }
}

唤醒头节点

private void unparkSuccessor(Node node) {
    int ws = node.waitStatus;
    // 可运行状态  
    if (ws < 0)
        compareAndSetWaitStatus(node, ws, 0);
    // 取消状态  
    Node s = node.next;
    if (s == null || s.waitStatus > 0) {
        s = null;
        for (Node t = tail; t != null && t != node; t = t.prev)
            if (t.waitStatus <= 0)
                s = t;
    }

    if (s != null)
        LockSupport.unpark(s.thread);
}

等待计数完成

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);
}

尝试是否确认计数完成

protected int tryAcquireShared(int acquires) {
    // 为0则计数完成返回,小于0则需要阻塞等待线程完成
    return (getState() == 0) ? 1 : -1;
}

尝试获取共享锁

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);
                // 锁计数为0,则全部线程已完成
                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);
    }
}

检查是否完成

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

设置等待线程为头节点和传播特性

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();
    }
}

恢复头节点运行状态

private void doReleaseShared() {
    for (;;) {
        Node h = head;
        // 头节点非空并且不是尾节点
        if (h != null && h != tail) {
            int ws = h.waitStatus;
            // 头节点等待unpark
            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;
    }
}

唤醒节点

private void unparkSuccessor(Node node) {
    int ws = node.waitStatus;
    // 节点等待条件,则更改状态为就绪
    if (ws < 0)
        compareAndSetWaitStatus(node, ws, 0);

    Node s = node.next;
    // 后排队节点不存在,或者被取消
    if (s == null || s.waitStatus > 0) {
        s = null;
        // 尾部往前寻找,找到最前面的等待运行节点
        for (Node t = tail; t != null && t != node; t = t.prev)
            if (t.waitStatus <= 0)
                s = t;
    }

    // 唤醒后置节点
    if (s != null)
        LockSupport.unpark(s.thread);
}