关于AQS与Condition的协作问题

来源:10-7 用条件对象实现生产者模式

Screenly

2021-05-16

问题1: 线程挂起和执行的代码位置

假设: 当生产者首次获得lock锁, 并进入到调用notEmpty.await();方法时, 会将当前的生产者线程存入到Condition等待队列中, 并且释放AQS中正在运行的Producer线程, 这个时候判断Producer线程是否在AQS中存在, 如果不存在, 这个时候会进入while (!isOnSyncQueue(node))循环, 执行LockSupport.park(this);停止当前线程

  • 问题1:执行LockSupport.park(this);方法, 代码的执行是停留在当前面吗?还是继续执行下面的逻辑代码?
    图片描述

  • 问题2: 为什么需要判断进入Condition队列的当前获得锁的线程在AQS中是否存在

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

本帖持续更新关于关于AQS与Condition的协作问题

写回答

1回答

悟空

2021-05-17

1 停留

2 可以看下这篇文章,写的挺好的:https://www.pianshen.com/article/3624315890/

0
1
Screenly
谢谢老师!!
2021-05-17
共1条回复

深度解密Java并发工具,精通JUC,成为并发多面手

JUC全方位讲解,构建并发工具类知识体系

1599 学习 · 573 问题

查看课程