专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

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 ,等待唤醒

简单图解

96_1.png

文章永久链接:https://tech.souyunku.com/42819

未经允许不得转载:搜云库技术团队 » Condition

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们