concurrent-5-AQS-Condition

本文深入解析了条件变量await方法的工作原理,包括响应中断、加入条件队列、释放锁资源、检查中断状态等关键步骤,并详细介绍了相关辅助方法如addConditionWaiter、unlinkCancelledWaiters、fullyRelease等的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

等待

await

 public final void await() throws InterruptedException {
            if (Thread.interrupted())  //响应中断
                throw new InterruptedException();
            Node node = addConditionWaiter();   //加入到条件队列尾
            int savedState = fullyRelease(node);  //返回aqs状态
            int interruptMode = 0;
            while (!isOnSyncQueue(node)) {   //查看当前节点是否在同步队列中,等待signal后会入同步队列
                LockSupport.park(this);   //不在同步队列中需要睡眠
                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)  //检查是否有被中断
                    break;
            }
            //尝试从队列中获取资源
            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
                interruptMode = REINTERRUPT;
            if (node.nextWaiter != null) // clean up if cancelled
                unlinkCancelledWaiters();  //清除非等待的节点
            if (interruptMode != 0)
                reportInterruptAfterWait(interruptMode);  //判断中断类型后进行相应的中断处理
        }

addConditionWaiter

private Node addConditionWaiter() {
            Node t = lastWaiter;    //condition 队列尾
            // 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;
        }

unlinkCancelledWaiters

 private void unlinkCancelledWaiters() {
            Node t = firstWaiter;  //获取头节点
            Node trail = null;    //临时节点
            while (t != null) {
                Node next = t.nextWaiter;   //获取下一节点
                if (t.waitStatus != Node.CONDITION) {   //如果当前节点不为条件等待
                    t.nextWaiter = null;    //清除t help gc
                    if (trail == null)  //如果临时节点为null
                        firstWaiter = next;  //则next节点为头节点
                    else
                        trail.nextWaiter = next;  //将当前节点过滤掉,
                    if (next == null)    //当next为null时,则表明到达了队列尾
                        lastWaiter = trail;
                }
                else
                    trail = t;  //将当前节点记录
                t = next;   //开始判断下一个节点
            }
        }

fullyRelease

 final int fullyRelease(Node node) {
        boolean failed = true;
        try {
            int savedState = getState();   //获取aqs状态
            if (release(savedState)) {  //尝试释放锁资源
                failed = false;
                return savedState;
            } else {
                throw new IllegalMonitorStateException();
            }
        } finally {
            if (failed)  //如果失败报错
                node.waitStatus = Node.CANCELLED;  //将节点标记为取消
        }
    }

isOnSyncQueue

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);  //从尾部遍历,如果不在队列中则返回false
    }

唤醒

signal

public final void signal() {
            if (!isHeldExclusively())  //如果当前线程不是持有锁的线程,则抛异常
                throw new IllegalMonitorStateException();
            Node first = firstWaiter;
            if (first != null)
                doSignal(first);  //将队列标记为signal 并入syc队列
        }

doSignal

private void doSignal(Node first) {
            do {
                if ( (firstWaiter = first.nextWaiter) == null)  //判断条件队列节点
                    lastWaiter = null;
                first.nextWaiter = null;
            } while (!transferForSignal(first) &&   //将条件队列入同步同列
                     (first = firstWaiter) != null);
        }

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

doSignalAll

  private void doSignalAll(Node first) {
            lastWaiter = firstWaiter = null;
            do {
                Node next = first.nextWaiter;
                first.nextWaiter = null;
                transferForSignal(first);  //一个个唤醒
                first = next;
            } while (first != null);
        }
### AQSCondition 的使用与原理详解 #### 1. Condition 的基本概念 Condition 是 Java 并发编程中的一个重要工具,它允许线程在特定条件下等待,直到其他线程满足条件后通知它们继续执行。Condition 必须与锁(Lock)关联使用,通常通过 `Lock.newCondition()` 方法创建[^3]。 #### 2. Condition 的实现原理 Condition 的实现基于同步器(AQS,AbstractQueuedSynchronizer)。每个 Condition 对象内部维护了一个双向链表队列,用于存储等待的线程。当调用 `await()` 方法时,当前线程会被加入到 Condition 的等待队列中,并释放锁;当调用 `signal()` 或 `signalAll()` 方法时,Condition 会将等待队列中的一个或所有线程转移到同步队列中,等待重新获取锁[^4]。 Condition 的核心逻辑由 `ConditionObject` 类实现,它是 AQS 的内部类。以下是 `ConditionObject` 的关键字段和方法: - **关键字段**: - `firstWaiter`:指向等待队列的第一个节点。 - `lastWaiter`:指向等待队列的最后一个节点。 - **关键方法**: - `await()`:使当前线程进入等待状态,并释放锁。 - `signal()`:唤醒等待队列中的一个线程,使其有机会重新获取锁。 - `signalAll()`:唤醒等待队列中的所有线程,使它们都有机会重新获取锁。 #### 3. Condition 的工作流程 以下是 Condition 的典型工作流程: - **await() 方法**: 1. 当前线程释放锁。 2. 将当前线程封装为一个节点(Node),并加入到 Condition 的等待队列中。 3. 当前线程进入等待状态,直到被唤醒、中断或超时[^4]。 - **signal() 方法**: 1. 从 Condition 的等待队列中移除第一个节点(即等待时间最长的线程)。 2. 将该节点加入到同步队列中,等待重新获取锁[^4]。 - **signalAll() 方法**: 1. 将 Condition 的等待队列中的所有节点都转移到同步队列中。 2. 所有等待的线程都有机会重新竞争锁[^4]。 #### 4. 示例代码 以下是一个简单的示例,展示了如何使用 Condition 实现线程间的等待与通知: ```java import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class ConditionExample { private final Lock lock = new ReentrantLock(); private final Condition condition = lock.newCondition(); private boolean isProduced = false; public void produce() throws InterruptedException { lock.lock(); try { System.out.println("Producer is producing..."); isProduced = true; condition.signal(); // 唤醒等待的消费者线程 } finally { lock.unlock(); } } public void consume() throws InterruptedException { lock.lock(); try { while (!isProduced) { System.out.println("Consumer is waiting..."); condition.await(); // 消费者线程进入等待状态 } System.out.println("Consumer is consuming..."); isProduced = false; } finally { lock.unlock(); } } public static void main(String[] args) throws InterruptedException { ConditionExample example = new ConditionExample(); Thread producer = new Thread(() -> { try { example.produce(); } catch (InterruptedException e) { e.printStackTrace(); } }); Thread consumer = new Thread(() -> { try { example.consume(); } catch (InterruptedException e) { e.printStackTrace(); } }); consumer.start(); Thread.sleep(100); // 确保消费者先启动 producer.start(); } } ``` #### 5. Condition 与直接使用 lock/unlock 的区别 直接使用 `lock` 和 `unlock` 进行等待和通知时,线程在等待期间不会释放锁,这可能导致死锁或其他问题。而 Condition 的 `await()` 方法会在等待时自动释放锁,`signal()` 方法则会唤醒等待的线程并允许其重新获取锁。 #### 6. 注意事项 - 调用 `await()`、`signal()` 和 `signalAll()` 方法时,必须持有相关的锁,否则会抛出 `IllegalMonitorStateException` 异常。 - `await()` 方法可能会因为虚假唤醒(spurious wakeup)而提前返回,因此建议在循环中使用条件判断[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值