V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
amiwrong123
V2EX  ›  Java

AQS 源码里,为什么 head 和 tail 是个成员变量而不是静态变量啊

  •  
  •   amiwrong123 · 2020-05-16 12:01:38 +08:00 · 1577 次点击
    这是一个创建于 1434 天前的主题,其中的信息可能已经有所发展或是发生改变。

    现在源码也没看完,但这点感觉好难理解啊。

        /**
         * Head of the wait queue, lazily initialized.  Except for
         * initialization, it is modified only via method setHead.  Note:
         * If head exists, its waitStatus is guaranteed not to be
         * CANCELLED.
         */
        private transient volatile Node head;
    
        /**
         * Tail of the wait queue, lazily initialized.  Modified only via
         * method enq to add new wait node.
         */
        private transient volatile Node tail;
    

    现在知道 CHL 队列 是一个 Node 的双向链表,而好多操作里面都需要获得 head/tail 成员(即每个 Node 都是知道,队列的 head 和 tail 是哪个 Node ),那这岂不是要时刻保持 双向链表里每个 Node 的 head 和 tail 都是正确的。

    那把 head 和 tail 设置为静态变量,岂不是方便了很多。反正同时只有一个 Node 是 head 嘛

    adguy
        1
    adguy  
       2020-05-16 13:45:59 +08:00
    现在知道 CHL 队列 是一个 Node 的双向链表,而好多操作里面都需要获得 head/tail 成员(即每个 Node 都是知道,队列的 head 和 tail 是哪个 Node )
    你的话到这里 都没毛病,

    那这岂不是要时刻保持 双向链表里每个 Node 的 head 和 tail 都是正确的。

    这一句也没毛病,但是 volatile 已经保证了每次获取到的都是最新的。


    那把 head 和 tail 设置为静态变量,岂不是方便了很多。反正同时只有一个 Node 是 head 嘛

    这有啥方不方便的呢?静态变量是为了不初始化类就能获取到,但是对于锁来说没必要,肯定是初始化锁了才会在内部调用头结点和尾节点。

    你这个问题挺无厘头的。。。。。。,乍一看有点蒙
    gexyuzz
        2
    gexyuzz  
       2020-05-16 14:08:46 +08:00
    你是想实现全局锁吗
    freebird1994
        3
    freebird1994  
       2020-05-16 14:16:18 +08:00
    用面向对象的角度是不是好理解些,每个锁持有一个队列,队列有头尾,与锁对象关联。而不是与这个类关联
    amiwrong123
        4
    amiwrong123  
    OP
       2020-05-16 21:30:17 +08:00 via Android
    @adguy
    @freebird1994
    @gexyuzz
    好吧,我发现我看错源码了,问了个 sb 的问题。此帖沉了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5362 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 06:45 · PVG 14:45 · LAX 23:45 · JFK 02:45
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.