JDK源码分析--多线程同步工具CountDownLatch类

来源:互联网 发布:pinnacle临床数据采集 编辑:程序博客网 时间:2024/06/13 22:53

CountDownLatch类运用了java开发模式中的策略模式。对线程作用的是CountDownLatch类中的内部类Sync。

Sync类继承了AbstractQueuedSynchronizer类,AbstractQueuedSynchronizer类是jdk多线程同步功能的重要类。CountDownLatch类有两个很重要的方法:await和countDown。这两个方法内分别调用的是AbstractQueuedSynchronizer的方法acquireSharedInterruptibly(int arg)和releaseShared(int arg)

CountDownLatch的逻辑是:使用CountDownLatch类,每个线程都公用一个初始化count的CountDownLatch对象常量,并在线程执行完成的时候调用countDown(),并在主线程使用await()进入阻塞状态,直到所有的任务完成,当count 减到0的时候开始执行主线程代码。

应用场景是:1.一个线程等待多个其它线程执行完成。多个线程等待其他多个线程执行完成。

这种多线程同步工具适用于在软件系统中,在开始某些任务前必须初始化一些系统数据,任务线程就必须等待系统数据初始化数据的完成,大型软件业务系统或计算系统就需要者同步工具。

CountDownLatch中重要 的两个方法:await()和countDown():

await():这个方法调用的是 sync.acquireSharedInterruptibly(1);

  public final void acquireSharedInterruptibly(int arg)            throws InterruptedException {        //检验当前线程是否设置了阻断标识位为true        if (Thread.interrupted())            throw new InterruptedException();        //尝试获取 分享模式下的锁        if (tryAcquireShared(arg) < 0)            doAcquireSharedInterruptibly(arg);    }
tryAcquireShared(int acquires)方法试图获取分享模式下的锁,这个方法由CountDownLatch类中的内部类Sync类实现,方法的源码如下:

        protected int tryAcquireShared(int acquires) {            return (getState() == 0) ? 1 : -1;        }
tryAcquireShared方法的意义是:同步锁的状态字段state为0,就返回-1,不为0就返回1.也就是说state的值为0,共享锁就能被线程获取,主线程能继续执行,如果是大于0,则表示主线程不能执行,并发生阻塞,进入锁的获取阻塞线程队列中去,可CountDownLatch类创建的时候会传进去一个值并赋给state属性。

共享锁获取成功后会执行doAcquireSharedInterruptibly(int arg)函数,该方法是将获取锁的等待线程都放入到阻塞队列中去,源代码如下:

    private void doAcquireSharedInterruptibly(int arg)        throws InterruptedException {    //同步等待队列中的头节点设置为空值的Node,表示同步锁处于共享模式        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) { //这里获取锁成功后,唤醒下一个AQS队列中的下一个线程,但当前的后继节点为当前线程,所以下面会将后继节点设置为head。                        setHeadAndPropagate(node, r);//激活下一个节点,本线程继续运行。                        p.next = null; // help GC                        failed = false;                        return;                    }                }                //如果获取共享锁失败,就挂起线程。                if (shouldParkAfterFailedAcquire(p, node) &&                    parkAndCheckInterrupt())                    throw new InterruptedException();                //在上面if中,线程被挂起阻塞了,当被唤醒后会继续执行循环            }        } finally {            if (failed)                cancelAcquire(node);        }    }
如果线程获取了共享锁,就调用setHeadAndPropagate()方法将下一个节点也激活(获取共享锁),这个激活的方法源码如下:

    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) 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) {            Node s = node.next;            if (s == null || s.isShared())                doReleaseShared();        }    }
首先使用setHead方法将头结点的后继节点设置为头节点,下面if语句中propagate>0表示AQS队列上的所有线程都能获取共享锁,然后如果下一个节点为共享模式线程节点(isShared())就将下一个节点唤醒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) {//如果头节点状态为signal(-1),即立刻唤醒头结点后驱节点指向的线程。                    if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))//如果头结点的状设置的原子操作失败,则重复设置。                        continue;            // loop to recheck cases                    unparkSuccessor(h);//唤醒head下个节点的线程。                }                else if (ws == 0 &&//如果头节点状态为0,即节点初始化状态,则直接设置头结点状态变为PROPAGATE(-3)                         !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))                    continue;                // loop on failed CAS            }            if (h == head)                   // loop if head changed                break;//循环在此结束,当head头节点没有发生变化        }    }

共享模式下,所有AQS队列下的线程都会被唤醒。

countDown()方法调用的是AQS类的releaseShared(1)方法,方法源码如下:

public final boolean releaseShared(int arg) {        if (tryReleaseShared(arg)) {            doReleaseShared();            return true;        }        return false;    }
tryReleaseShared(1)返回成功后就执行doReleaseShared方法。tryReleaseShared方法是将state值减掉个1,并赋给它值。如果state值本来就是0,则返回false,只有当

当state减去1后值为0的时候,函数返回true。然后就将AQS中所有的阻塞线程都依次唤醒。

总结:到这里我们可以看到,在这个多线程同步模式下,如果你有number个线程需要提前执行完成,你就需要创建stae值为number的CountDownLatch类对象c,然后将对象c

的值传给我们提前执行的线程和需要等待执行的线程。在这两中线程中分别调用c对象的countDown方法和await方法。在此主要实现这个功能的类是AQS类。不过这个同步锁是一个

共享锁,而不是以前接触的独占锁,两种模式的区别是:共享锁等待队列中,只要一个节点获取了锁,那么所有的节点都能获取锁,而独占模式就不一样了,一个阻塞节点是要唯一拥有

锁的。

以上就是对多线程同步工具类CountDownLatch的源码原理分析。





原创粉丝点击