部分启发来源自文章:Java并发编程--Lock

PART 1

1、如果h==t成立,h和t均为null或是同一个具体的节点,无后继节点,返回false。
2、如果h!=t成立,head.next是否为null,如果为null,返回true。什么情况下h!=t的同时h.next==null??,有其他线程第一次正在入队时,可能会出现。见AQS的enq方法,compareAndSetHead(node)完成,还没执行tail=head语句时,此时tail=null,head=newNode,head.next=null。
3、如果h!=t成立,head.next != null,则判断head.next是否是当前线程,如果是返回false,否则返回true(head节点是获取到锁的节点,但是任意时刻head节点可能占用着锁,也可能释放了锁(unlock()),未被阻塞的head.next节点对应的线程在任意时刻都是有必要去尝试获取锁)

 public final boolean hasQueuedPredecessors() {
Node t = tail;
Node h = head;
Node s;
return h != t &&
((s = h.next) == null || s.thread != Thread.currentThread());
}

PART 2  解释为什么要判断:s.thread != Thread.currentThread()

评论区3楼的提问差点让我以为我这里理解错并写错了,现在是12月,文章是4月份写的,都快忘光了...仔细再把文章和源码读了读,发现本文写的确实不够详细,有个地方还写的有点问题,漏了一些细节,因此来补充一下。  ---20191217

1、

根据ReentrantLock的解锁流程,也就是下面四个方法,可以看到当线程释放锁之后还是会在队列的head节点,但会把head的后续可唤醒节点进行唤醒(unpark)
也就是说任意时刻,head节点可能占用着锁(除了第一次执行enq()入队列时,head仅仅是个new Node(),没有实际对应任何线程,但是却“隐式”对应第一个获得锁但并未入队列的线程,和后续的head在含义上保持一致),也可能释放了锁(unlock()),未被阻塞的head.next节点对应的线程在任意时刻都是有必要去尝试获取锁

 public void unlock() {
sync.release(1);
}

2、

尝试释放锁,释放成功后把head.next从阻塞中唤醒

从这里以及后续的3和4可以看出,虽然线程已经释放了锁(state设置为0),但是并没有把head指向链表的下个节点(即进行类似head = head.next的操作)

这里就对应的第1点里说的,如果这里能看到,那么久可以直接看第5点了

 public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return false;
}

3、

把state-1
当state=0时,把exclusiveOwnerThread设置为null,说明线程释放了锁

 protected final boolean tryRelease(int releases) {
int c = getState() - releases;
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
setState(c);
return free;
}

4、

把head.next指向下一个waitStatus<=0的节点,并把该节点从阻塞中唤醒

 private void unparkSuccessor(Node node) {
int ws = node.waitStatus;
if (ws < 0)
compareAndSetWaitStatus(node, ws, 0); Node s = node.next;
if (s == null || s.waitStatus > 0) {
// 这里没看懂为什么要从tail节点倒序遍历?
// 不是应该从head.next节点开始遍历更快嘛?
s = null;
for (Node t = tail; t != null && t != node; t = t.prev)
if (t.waitStatus <= 0)
s = t;
}
if (s != null)
LockSupport.unpark(s.thread);
}

5、

需要提前知道一点:hasQueuedPredecessors()方法只在tryAcquire()方法里面被调用执行过,hasQueuedPredecessors()返回false表示要尝试获取锁

线程加锁的流程是:.lock() -> .acquire() -> tryAcquire()

这里我们先假设一个场景:A线程获取到了锁,然后B线程尝试去获取锁但是获取不到,此时链表的head是对用A线程,head.next对应B线程

当在B线程在第2行的tryAcquire()里面无法获取到锁时,线程B会通过下面第3行的addWaiter()方法被加入到等待链表当中,然后在第3行的acquireQueued()方法和第38行的parkAndCheckInterrupt()中park进入等待状态

在A线程释放锁之后,B线程会从38行处开始重新苏醒然后进入for(;;)循环,当B线程执行到第28行即再次执行tryAcquire()时,然后就会依次执行hasQueuedPredecessors()和s.thread != Thread.currentThread()。由前文可知,此时head仍然指向A线程,head.next也就是此处的s指向的是B线程,也同时是当前线程,所以s.thread != Thread.currentThread()为false,即此时需要尝试获取锁(再次重复这句话:未被阻塞的head.next节点对应的线程在任意时刻都是有必要去尝试获取锁)。

当此处B线程终于获得锁之后,会在第30行处把head指向B线程对应的链表结点。

 public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
} protected final boolean tryAcquire(int acquires) {
// 省略部分不重要的 if (c == 0) {
if (!hasQueuedPredecessors() &&
compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
} // 省略部分不重要的
} final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
final Node p = node.predecessor();
// 这里又执行了tryAcquire
if (p == head && tryAcquire(arg)) {
// 把head指向当前节点
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
// 获取不到锁,会在此处进入线程等待状态
// 后续被唤醒的话,也是从这里出来,然后继续for循环
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}

最新文章

  1. BI分析受阻?FineBI推出SPA螺旋式分析新功能!
  2. 【整理】Linux下中文检索引擎coreseek4安装,以及PHP使用sphinx的三种方式(sphinxapi,sphinx的php扩展,SphinxSe作为mysql存储引擎)
  3. phoneGap蓝牙设备链接打印操作插件
  4. android/java 根据当前时间判断股票交易状态(未开盘 交易中 休市中 已收盘)
  5. HDU 3874 Necklace (树状数组 | 线段树 的离线处理)
  6. 干货分享:IBM StorwizeV7000部署与运维
  7. poj1673EXOCENTER OF A TRIANGLE
  8. 前端javascript发送ajax请求、后台书写function小案例
  9. 1427. SMS(DP)
  10. WP-PostViews Plus停止计数
  11. Java设计模式05:常用设计模式之原型模式(创建型模式)
  12. 转:MySQL导入.sql文件及常用命令
  13. unix命令: ifconfig
  14. valid number 判断字符串是否为有效数字
  15. bzoj 2753: [SCOI2012]滑雪与时间胶囊
  16. C#的LINQ
  17. docker iotop :OSError: Netlink error: No such file or directory
  18. jdk5升级至jdk8框架版本选型
  19. 解决安装虚拟环境出现的问题(OSError: Command /home/python/.virtua...ngo3_web/bin/python3 - setuptools pkg_resources pip wheel failed with error code 2)
  20. Direct3D驱动类型(DRIVER_TYPE)介绍

热门文章

  1. 一个SAP开发人员的2017总结
  2. kahadb设计
  3. log4net 配置完成后发现不能输出日志的解决方法
  4. Android学习笔记_73_授权过程
  5. GOPL第三章练习题3.3 3.4代码
  6. SpringBoot非官方教程 | 终章:文章汇总
  7. toad安装错误—Failed to Download products and updates
  8. [oracle]索引与索引表管理
  9. Python实现trim函数
  10. alias,unalias命令