前两节你应该把握了ReentrantLock加锁胜利和加锁失败入队的外围逻辑,是如何通过AQS中的3个组件做到的。明天来咱们看下:

ReentrantLock中,当线程开释锁时的逻辑

开释锁的过程及源码分析

<div class="output_wrapper" id="output_wrapper_id" style="width:fit-content;font-size: 16px; color: rgb(62, 62, 62); line-height: 1.6; word-spacing: 0px; letter-spacing: 0px; font-family: 'Helvetica Neue', Helvetica, 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif;"><h3 id="hdddd" style="width:fit-content;line-height: inherit; margin: 1.5em 0px; font-weight: bold; font-size: 1.3em; margin-bottom: 2em; margin-right: 5px; padding: 8px 15px; letter-spacing: 2px; background-image: linear-gradient(to right bottom, rgb(43,48,70), rgb(43,48,70)); background-color: rgb(63, 81, 181); color: rgb(255, 255, 255); border-left: 10px solid rgb(255,204,0); border-radius: 5px; text-shadow: rgb(102, 102, 102) 1px 1px 1px; box-shadow: rgb(102, 102, 102) 1px 1px 2px;"><span style="font-size: inherit; color: inherit; line-height: inherit; margin: 0px; padding: 0px;">开释锁的过程及源码分析</span></h3></div>

目前通过线程1、线程2应用ReentrantLock.lock()后的后果如下:

线程2入队期待,线程1持有锁,state=1,owner是线程1,队列中元素是线程2,队列是由Node节点组成的双向链表,头结点为空,队列具体情况如下:

此时假如线程1调用了unlock()办法,进行开释锁,会做哪些事件呢?

首先咱们来看一下开释的代码:

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

非常简单,还是应用Sync组件(AQS)来开释锁。release()办法

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

外围分为了2步:

1) tryRelease办法,开释state和owner变量

2) unparkSuccessor办法,唤醒队列元素

别离来看一下,首先开释变量tryRelease办法:

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

这个办法逻辑很清晰,以后线程是线程1,state=1,入参releases是1,示意开释一次锁。很显著,state减1后变为0,会将owner也置为空,示意以后没有线程持有锁了,之后设置state为0完结。

整个过程如下图所示:

批改了owner和state两个组件的值后,第二步就是唤醒队列期待的线程了。

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

首先开释胜利锁后,应用了h指针指向了以后队列的头部,判断一下队列中是否有期待的元素,留神对头元素waitStatus不能是0,如果是0,阐明队列只有一个空节点,队列中没有期待元素。因为入队元素后会将头结点的waitStatus改成-1,SIGNAL。

接着进入了unpartSuccessor办法。从名字看就是复原在h节点之后挂起的线程。(PS:JDK源码外面总会呈现一些语义相近的词语,比方first-last,head-tail,successor- predecessor,prev-next,其实都是示意前后的意思,是等价的,这点大家要分明。)

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

node就是入参h,head节点,首先把head节点waitStatus从-1改为0。

接着s=node.next示意的就是线程2排队的Node,s不为空,执行了LockSupport.unpark(s.thread); 将线程2进行了唤醒。

最初整个办法返回,release返回true示意开释锁胜利。如下图所示:

此时之前被挂起的线程2,还记得吗?就是线程2已经执行了LockSupport.park(t)的操作,线程被挂起,代码会hang在那一行期待。

private final boolean parkAndCheckInterrupt() {  LockSupport.park(this);  return Thread.interrupted();}

线程2就会接着执行,只有线程2没被打断过,返回的必定是false,以下的if条件不会成立。

 if (shouldParkAfterFailedAcquire(p, node) &&parkAndCheckInterrupt())

接着回到for循环,从新进行tryAcquire操作,线程2再次尝试获取锁,此时假如没有别的线程过去加锁。线程2天然就会获取锁,设置state=1,owner=线程2了。

final boolean acquireQueued(final Node node, int arg) {  boolean failed = true;  try {    boolean interrupted = false;    for (;;) {      final Node p = node.predecessor();      if (p == head && tryAcquire(arg)) {        setHead(node);        p.next = null; // help GC        failed = false;        return interrupted;      }      if (shouldParkAfterFailedAcquire(p, node) &&        parkAndCheckInterrupt())        interrupted = true;    }  } finally {    if (failed)      cancelAcquire(node);  }}

下面整个开释锁的过程能够总结如下图:

思考&长图总结ReentrantLock

<div class="output_wrapper" id="output_wrapper_id" style="width:fit-content;font-size: 16px; color: rgb(62, 62, 62); line-height: 1.6; word-spacing: 0px; letter-spacing: 0px; font-family: 'Helvetica Neue', Helvetica, 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif;"><h3 id="hdddd" style="width:fit-content;line-height: inherit; margin: 1.5em 0px; font-weight: bold; font-size: 1.3em; margin-bottom: 2em; margin-right: 5px; padding: 8px 15px; letter-spacing: 2px; background-image: linear-gradient(to right bottom, rgb(43,48,70), rgb(43,48,70)); background-color: rgb(63, 81, 181); color: rgb(255, 255, 255); border-left: 10px solid rgb(255,204,0); border-radius: 5px; text-shadow: rgb(102, 102, 102) 1px 1px 1px; box-shadow: rgb(102, 102, 102) 1px 1px 2px;"><span style="font-size: inherit; color: inherit; line-height: inherit; margin: 0px; padding: 0px;">思考&长图总结ReentrantLock</span></h3></div>

咱们剖析ReentrantLock的加锁和开释锁,明天最初小结的一个思维其实就是:由脉络到细节,再从细节脉络。

另外 为了让大家更好的把握ReentrantLock的AQS原理。这里给大家总结了一下。,

首先能够把原理用一句话简略的讲:假如有两个线程同时进行获取锁的操作,只能有一个获取胜利,另一个会进入一个队列期待。底层是联合了state、owner,Node队列AQS的3个组件配合起来做到的。

ReentrantLock外围加锁和开释流程能够总结为如下一张长图:

本文由博客一文多发平台 OpenWrite 公布!