CountLauthDown源码解析

应用场景

主线程等待子线程完成后继续执行

public class CountDownLatchTest1 {


    private CountDownLatch latch = new CountDownLatch(30);

    public CountDownLatch getLatch() {
        return latch;
    }

    public static void main(String[] args) {
        CountDownLatchTest1 test = new CountDownLatchTest1();
        List<Thread> threadList = new ArrayList<>();
        for (int i = 0; i < 30; i++) {
            Thread thread = new A(i, test.getLatch());
            threadList.add(thread);
        }
        for (Thread thread : threadList) {
            thread.start();
        }

        try {
            test.getLatch().await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("主线程结束");
    }

}

class A extends Thread {
    private static Random random = new Random();
    private int i;
    private CountDownLatch latch;
    public A(int i, CountDownLatch latch) {
        this.i = i;
        this.latch = latch;
    }

    @Override
    public void run() {
        long time = random.nextInt(10) * 1000L;
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        latch.countDown();
        System.out.println(this.i  + "号子线程睡眠:" + time);
    }
}

new CountDownLatch(int)

先看CountDownLatch的构造函数做了什么

    /**
     * Constructs a {@code CountDownLatch} initialized with the given count.
     *
     * @param count the number of times {@link #countDown} must be invoked
     *        before threads can pass through {@link #await}
     * @throws IllegalArgumentException if {@code count} is negative
     */
    public CountDownLatch(int count) {
        if (count < 0) throw new IllegalArgumentException("count < 0");
        this.sync = new Sync(count);
    }
        private static final class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = 4982264981922014374L;

        Sync(int count) {
            //设置aqs的state属性
            setState(count);
        }
        ...

可以看到构造函数创建了内部类Sync实例,Sync是继承与AQS(AbstractQueuedSynchronizer)的,Sync的构造函数调用了AQS#setState将AQS的state属性初始化了

CountDownLatch#await

    /**
     * Causes the current thread to wait until the latch has counted down to
     * zero, unless the thread is {@linkplain Thread#interrupt interrupted}.
     *(引起当前线程等待直到latch的count减少为0,除非线程被中断了)
     *
     * <p>If the current count is zero then this method returns immediately.
     *(如果当前count是0那么这个方法会立刻返回)
     * <p>If the current count is greater than zero then the current
     * thread becomes disabled for thread scheduling purposes and lies
     * dormant until one of two things happen:
     *(如果当前count比0大然后当前线程将休眠至以下两件事情之一发生:)
     * <ul>
     * <li>The count reaches zero due to invocations of the
     * {@link #countDown} method; or
     * <li>Some other thread {@linkplain Thread#interrupt interrupts}
     * the current thread.
     *(count到达0,由于countDown的调用;或者一些其他线程中断了当前线程)
     * </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.
     *
     * @throws InterruptedException if the current thread is interrupted
     *         while waiting
     */
    public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

sync#acquireSharedInterruptibly
实际调用的父类AQS#acquireSharedInterruptibly

    /**
     * Acquires in shared mode, aborting if interrupted.  Implemented
     * by first checking interrupt status, then invoking at least once
     * {@link #tryAcquireShared}, returning on success.  Otherwise the
     * thread is queued, possibly repeatedly blocking and unblocking,
     * invoking {@link #tryAcquireShared} until success or the thread
     * is interrupted.
     * @param arg the acquire argument.
     * This value is conveyed to {@link #tryAcquireShared} but is
     * otherwise uninterpreted and can represent anything
     * you like.
     * @throws InterruptedException if the current thread is interrupted
     */
    public final void acquireSharedInterruptibly(int arg)
            throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
            //①
        if (tryAcquireShared(arg) < 0)
            //②
            doAcquireSharedInterruptibly(arg);
    }

这个方法之前信号量Semaphore里已经出现过了,唯一不同的是tryAcquireShared方法是由具体的子类实现的,下面看一下CountLauthDown的实现:

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

可以看到实现非常简单,逻辑就是判断state等不等于0,如果等于0就返回1, 不然返回-1,如果是-1,就会调用 ② doAcquireSharedInterruptibly,
否则方法就结束了,当前线程不会被阻塞,下面看下doAcquireSharedInterruptibly

/**
     * 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;
                    }
                }
                //是否需要park休眠,如果休眠了,被唤醒后需要检查有没有被中断,这里的逻辑不再赘述,之前几篇文章这个方法以及讲过了
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

这里仔细看一下setHeadAndPropagate方法做了什么事情

    /**
     * Sets head of queue, and checks if successor may be waiting
     * in shared mode, if so propagating if either propagate > 0 or
     * PROPAGATE status was set.
     *
     * @param node the node
     * @param propagate the return value from a tryAcquireShared
     */
    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.
         */
        //如果propagate大于0 并判断node的next节点是不是空的或者是共享模式节点,是的话就传播唤醒下一个节点
        if (propagate > 0 || h == null || h.waitStatus < 0 ||
            (h = head) == null || h.waitStatus < 0) {
            Node s = node.next;
            if (s == null || s.isShared())
                doReleaseShared();
        }
    }

这段代码可以传递唤醒节点,比如CountDownLatch不只一个线程await(),之后其他线程countDown将state减少到0,唤醒第一个节点后,如果不传递唤醒,那么只能唤醒一个线程,所以需要有这个传递的机制

CountDownLatch#countDown

    /**
     * Decrements the count of the latch, releasing all waiting threads if
     * the count reaches zero.
     *(减少latch的count,释放所有等待)
     * <p>If the current count is greater than zero then it is decremented.
     * If the new count is zero then all waiting threads are re-enabled for
     * thread scheduling purposes.
     *
     * <p>If the current count equals zero then nothing happens.
     */
    public void countDown() {
        sync.releaseShared(1);
    }

AQS#releaseShared

    /**
     * Releases in shared mode.  Implemented by unblocking one or more
     * threads if {@link #tryReleaseShared} returns true.
     *
     * @param arg the release argument.  This value is conveyed to
     *        {@link #tryReleaseShared} but is otherwise uninterpreted
     *        and can represent anything you like.
     * @return the value returned from {@link #tryReleaseShared}
     */
    public final boolean releaseShared(int arg) {
        //①
        if (tryReleaseShared(arg)) {
            //②
            doReleaseShared();
            return true;
        }
        return false;
    }

①Sync#tryReleaseShared

    protected boolean tryReleaseShared(int releases) {
            // Decrement count; signal when transition to zero
            //减少state的值
            for (;;) {
                int c = getState();
                if (c == 0)
                    return false;
                int nextc = c-1;
                if (compareAndSetState(c, nextc))
                    //如果减少到0,说明可以唤醒阻塞的线程了
                    return nextc == 0;
            }
        }

② AQS#doReleaseShared 唤醒同步队列里休眠的线程,这个方法之前也讲过了

    /**
     * Release action for shared mode -- signals successor and ensures
     * propagation. (Note: For exclusive mode, release just amounts
     * to calling unparkSuccessor of head if it needs signal.)
     */
    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;
        }
    }
posted @ 2020-04-18 15:54  鹿慕叶  阅读(247)  评论(0编辑  收藏  举报