Java Condition 解析

condition.await()

1. 代码总览

public final void await() throws InterruptedException {
            if (Thread.interrupted())
                throw new InterruptedException();
            Node node = addConditionWaiter();                                                       (1)
            int savedState = fullyRelease(node);                                                    (2)
            int interruptMode = 0;
            while (!isOnSyncQueue(node)) {                                                          (3)
                LockSupport.park(this);
                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
                    break;
            }
            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)                       (4)
                interruptMode = REINTERRUPT;
            if (node.nextWaiter != null) // clean up if cancelled
                unlinkCancelledWaiters();
            if (interruptMode != 0)
                reportInterruptAfterWait(interruptMode);
 }

2. 分段解析

2.1 addConditionWaiter()
private Node addConditionWaiter() {
            Node t = lastWaiter;
            // If lastWaiter is cancelled, clean out.
            if (t != null && t.waitStatus != Node.CONDITION) {
                unlinkCancelledWaiters();
                t = lastWaiter;
            }
            Node node = new Node(Thread.currentThread(), Node.CONDITION);
            if (t == null)
                firstWaiter = node;
            else
                t.nextWaiter = node;
            lastWaiter = node;
            return node;
}

这个方法的话,简单来说就是会构建一个 Condition 队列 , 有一个 lastWaiter 和 firstWaiter ,它和 AQS 的同步队列,区别在于 AQS队列是双向的,而Condition 队列是单向的

  • Condition 的几种状态
        /** waitStatus value to indicate thread has cancelled */
        static final int CANCELLED =  1;
        /** waitStatus value to indicate successor's thread needs unparking */
        static final int SIGNAL    = -1;
        /** waitStatus value to indicate thread is waiting on condition */
        static final int CONDITION = -2;
        /**
         * waitStatus value to indicate the next acquireShared should
         * unconditionally propagate
         */
        static final int PROPAGATE = -3;
  • 首先会去获取 Last Node 节点
  • 如果这个 Node 节点不为空而且状态值不等于 -1 ,这时 Node 的状态处于 CANCELLED 状态,会将其从队列中去除
  • 当是第一次进来的时候, t 肯定是 Null ,这时会新建一个 Node 节点,并设置为 firstWaiter 节点,将这个节点返回
2.2 fullyRelease()
final long fullyRelease(Node node) {
        boolean failed = true;
        try {
            long savedState = getState();
            if (release(savedState)) {
                failed = false;
                return savedState;
            } else {
                throw new IllegalMonitorStateException();
            }
        } finally {
            if (failed)
                node.waitStatus = Node.CANCELLED;
        }
 }

因为它是可重入锁,所以这里在进行释放的时候,是获取到该锁的进入次数全部释放的,

如果释放失败的话,failed = true ,这就会将 Node 的状态设置为 CANCELLED ,之后会将这个节点移除。

2.3 while 循环判断
while (!isOnSyncQueue(node)) {
               LockSupport.park(this);
               if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
                    break;
}
final boolean isOnSyncQueue(Node node) {
        if (node.waitStatus == Node.CONDITION || node.prev == null)
            return false;
        if (node.next != null) // If has successor, it must be on queue
            return true;
        /*
         * node.prev can be non-null, but not yet on queue because
         * the CAS to place it on queue can fail. So we have to
         * traverse from tail to make sure it actually made it.  It
         * will always be near the tail in calls to this method, and
         * unless the CAS failed (which is unlikely), it will be
         * there, so we hardly ever traverse much.
         */
        return findNodeFromTail(node);
    }

主要的核心就是 isOnSyncQueue 方法,判断该节点是否在 AQS 队列中

  • status = CONDITION ,node.prev == null
  • CONDITION 的话,代表是从 addConditionWaiter() 方法创建出来的,肯定不在 AQS 队列中
  • 在 AQS 队列中,head 节点也就是获取到锁的节点,而 head 节点的 Prev 是 null, 这时也可以表明它不在 AQS 队列中

判断不在 AQS 中,执行 park 方法,进行挂起,这时锁已经释放,该线程已经挂起,别的线程就可以抢占到锁,别的线程执行 singal 之后,会执行后续代码,尝试获取锁,进行执行。

condition.signal()

1. 代码总览

public final void signal() {
            if (!isHeldExclusively())
                throw new IllegalMonitorStateException();
            Node first = firstWaiter;
            if (first != null)
                doSignal(first);
        }
private void doSignal(Node first) {
            do {
                if ( (firstWaiter = first.nextWaiter) == null)
                    lastWaiter = null;
                first.nextWaiter = null;
            } while (!transferForSignal(first) &&
                     (first = firstWaiter) != null);
        }

do while 循环,首先执行一次do , 将 first 和 condition 队列切断联系,然后执行while 里面的 transferForSignal

2. 分段解析

2.1 transferForSignal()
final boolean transferForSignal(Node node) {
        /*
         * If cannot change waitStatus, the node has been cancelled.
         */
        if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
            return false;

        /*
         * Splice onto queue and try to set waitStatus of predecessor to
         * indicate that thread is (probably) waiting. If cancelled or
         * attempt to set waitStatus fails, wake up to resync (in which
         * case the waitStatus can be transiently and harmlessly wrong).
         */
        Node p = enq(node);
        int ws = p.waitStatus;
        if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
            LockSupport.unpark(node.thread);
        return true;
    }
  • enq() 将 node 加入到 AQS 队列中
  • CAS 进行状态更改,若更改失败,代表为 取消状态
  • 当前状态为取消状态,或者设置状态为 Signal 失败,则调用 unpark 进行释放
  • 如果一切正常,这时 node 节点的状态为 SIGNAL ,等待唤醒

简单图解

Condition.png

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值