知识总结

hasQueuedPredecessors()解析

判断队列是否有等待资源的线程

public final boolean hasQueuedPredecessors() {
    //读取尾节点
    Node t = tail; 
   //读取头节点
    Node h = head;
    //s是首节点h的后继节点
    Node s;
    return h != t &&
        ((s = h.next) == null || s.thread != Thread.currentThread());
}
  1. h != t 什么时候是false 就是首尾节点相同时
    (1) 首尾节点都是空的 说明队列是空的,无须等待,返回true
    (2) 首尾节点都不是空的 而且指向同一个内容,说明队列内只有一个节点,无须等待,返回false
  2. h != t 什么时候是true 就是首尾节点不相同时,说明队列中至少有两个不同节点
  3. h != t 返回true,(s = h.next) == null返回true
    因为在当前线程还在做尝试获取同步状态的操作时,已经有另一个线程准备入队了,当前线程慢人一步,自然就得去排队。
  4. h != t 返回true,(s = h.next) == null返回false,s.thread != Thread.currentThread()返回true。
    (s = h.next) == null返回false表示首节点是有后继节点的。
    s.thread != Thread.currentThread()返回true表示后继节点的相关线程不是当前线程,所以首节点虽然有后继节点,但是后继节点相关的线程却不是当前线程,那当前线程自然得老老实实的去排队。
posted @ 2021-06-25 09:50  CalronLoveRonnie  阅读(44)  评论(0编辑  收藏  举报
AmazingCounters.com