jdk-AbstractQueuedSynchronizer(二)

上一篇分析只是基于AQS本身去分析了一下队列的逻辑,其实也只是分析了独占锁的模式,今天再来看看共享锁的模式是什么样的。

共享锁的话可以基于CountDownLatch去分析,CountDownLatch这个是个倒数计数器,其实是一个工具,可将一个任务分解到多线程中分别执行一段。我们就基于此分析一下共享锁。。

先上一段CountDownLatch 的例子。可以看见每个线程中都执行了begin.wait()方法,这个方法会在begin执行到0时才开始执行,类似中断当前线程的运行,等待一个状态。

end也是执行了一个wait(),在end到0时才会去执行。

/**
 * 同步计数器
 * Created by Administrator on 17-5-2.
 */
public class CountDownLatchTest {

    public static final int TOTALNUM = 10;

    public static void main(String[] args) throws InterruptedException{

        /*开始倒计时 计数器*/
        final CountDownLatch begin = new CountDownLatch(10);

        /*结束倒计时 计数器*/
        final CountDownLatch end = new CountDownLatch(TOTALNUM);

        ExecutorService service = Executors.newFixedThreadPool(TOTALNUM);

        for(int i = 0; i < TOTALNUM; i++){
            final int num = i + 1;

            Runnable run = new Runnable() {
                @Override
                public void run() {
                    try{
                        //所有线程等待开始计数器倒数至0
                        begin.await();

                        System.out.println("This is gunner: " + num);

                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }finally {
                        //每次到达一个 -1
                        end.countDown();
                    }
                }
            };

            service.submit(run);
        }

        for(int i = TOTALNUM; i > 0; i--){
            begin.countDown();
        }

        end.await();

        System.out.println("all people arrive: end");

        service.shutdown();

    }

}
那么在CountDownLatch里,这个0其实就是一个状态。

首先看初始化方法,其实就是将一个数目存放进了state字段中,这个state在不同的场景中代表不同的含义,在CountDownLatch中代表计数器的大小。

public CountDownLatch(int count) {
        if (count < 0) throw new IllegalArgumentException("count < 0");
        this.sync = new Sync(count);
    }
protected final void setState(int newState) {
        state = newState;
    }
初始化之后紧接着就是wait方法,看它做了什么?如果当前线程被打断了,直接抛出异常,不看。

看它接着在做什么,

public final void acquireSharedInterruptibly(int arg)
            throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
        if (tryAcquireShared(arg) < 0)
            doAcquireSharedInterruptibly(arg);
    }
tryAcquireShared是由子类实现的,去看CountDownLatch内的方法,超级easy,判断计数器的大小是多少~~~如果是0,则返回1,不是则是 -1。回头看上面的方法,一般情况下我们假设现在计数器还有,这个是一般情况,那么存在计数器大小不为0,也就对应开头所说,知道为0时才执行。。。
 protected int tryAcquireShared(int acquires) {
            return (getState() == 0) ? 1 : -1;
        }
小于0时,执行下面的逻辑。addWaiter方法跟昨天看的一致,轮询去建立一个head的空节点和子节点。并设置tail指向当前节点,注意这块,head处是一个空节点,真正村春当前线程的是后继节点,这一点要搞清楚,认真看下源码中的enq方法就能发现了。至于shouldParkAfterFailedAcquire和parkAndCheckInterrupt方法就不说了,跟之前一样,将当前节点的状态设置成SiNGAL,并阻塞当前节点,我们来看下不同点是对于前驱节点的处理。

首先获取当前节点的前驱节点,判断是不是head节点。如果是的话,再次尝试获取锁,此时如果计数器还没到0的话,就会返回-1,说明线程还不能执行,直接到后面逻辑,阻塞当前线程。如果当前线程执行时刚好计数器大小为0了,说明可以执行了。就会去执行setHeadAndPropagate方法,这个方法又在干什么?我们知道p.next和之前一样,其实就是将head处的空节点释放掉了。

    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);
        }
    }
看下这个方法 setHead,顾名思义了,将当前节点设置成头节点,并将其中的Thread 设置成null,并将当前节点指向的head处节点断掉。

 private void setHead(Node node) {
        head = node;
        node.thread = null;
        node.prev = null;
    }
因此就进入了release流程。进入release流程,是release谁呢?release的是下一个节点,这个就很有趣了,当前节点获取锁成功了,要唤醒下一个节点。实现了共享状态向后传递的效果。
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();
        }
    }
看下release过程。如果当前线程的状态是SINGAL时,唤醒下一个节点。如果不是,状态为0时,设置为PROPAGATE,这个状态是个传播状态。如果当前操作过程中h被别的线程改过了,那么当前线程再次进入轮训。那么唤醒的下一个线程又从doAcquireSharedInterruptibly方法开始找寻前驱节点是不是head,进入再次唤醒下一个节点的流程。

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

示例如下: 对于例子中新起的10个线程,由于执行了,begin.wait()操作,那么在wait操作过程中,它们不断的轮训看能不能获取到锁,但是可惜的是state设置的大小是10,它们永远走不到return的那一步,所以最终它们都在doAcquireSharedInterruptibly方法中断了自己,并且最终状态都是-1,也就是等待某个条件唤醒自己。


以上就是中断逻辑,那么现在来看什么时候能唤醒呢?其实跟第一篇分析的有所不同,这边的唤醒条件就是计数器为0,也即是countDown执行为0时,很巧妙的一个实现啊。

可见每执行一次,都是减1啊,所以这叫做倒数计数器嘛。

 public void countDown() {
        sync.releaseShared(1);
    }
tryReleaseShared方法由子类实现。看见这个方法只要结果不是0,就一直是false,直至倒数计数器的值为0。
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;
            }
        }
下一步就是去唤醒上面中断的线程。方法任然是doReleaseShared方法。那么现在线程会重新去获取锁了,此时的tryAccquireShared方法内state为0了,返回的是1,进入了setHead流程,再次循环了。

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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值