欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

ReentrantLock可重入鎖原理解析

 更新時(shí)間:2023年10月27日 09:24:25   作者:lane  
這篇文章主要為大家介紹了ReentrantLock可重入鎖原理解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

ReentrantLock 可重入鎖

字面意思理解為同一線程可以重入加鎖

內(nèi)部主要邏輯繼承AQS來(lái)實(shí)現(xiàn)的,有兩種實(shí)現(xiàn)FairSycn、NonfairSync,公平鎖和非公平鎖,默認(rèn)為非公平鎖。

  • 公平鎖:保證先入隊(duì)的先獲得鎖。
  • 非公平鎖:不保證先入隊(duì)的先獲得鎖,可能后面的線程先搶到鎖。

主要實(shí)現(xiàn)流程

CAS全名compare and swap比較交換,由native方法提供的系統(tǒng)原子性操作,以保證并發(fā)發(fā)安全性。

公平鎖的實(shí)現(xiàn)

加鎖

//加鎖
final void lock() {
  acquire(1);//調(diào)用AQS方法
}
//AQS方法
public final void acquire(int arg) {
  if (!tryAcquire(arg) &&//嘗試獲取鎖,抽象方法由子類實(shí)現(xiàn)
      acquireQueued(addWaiter(Node.EXCLUSIVE), arg))    
      /* addWaiter 將線程加入等待隊(duì)列
       * acquireQueued 嘗試獲取鎖、阻塞
       */
  {
      //中斷
      selfInterrupt();
  }
}
//嘗試獲取鎖
protected final boolean tryAcquire(int acquires) {
  //獲取當(dāng)前線程
  final Thread current = Thread.currentThread();
  int c = getState();//獲取state值,AQS屬性volatile標(biāo)記
  if (c == 0) {//鎖空閑狀態(tài)
      if (!hasQueuedPredecessors() &&//是否需要排隊(duì)
          compareAndSetState(0, acquires)) {//獲取鎖
          setExclusiveOwnerThread(current);//成功獲取,設(shè)置鎖owner為當(dāng)前線程
          return true;//后續(xù)不在處理
      }
  }
  else if (current == getExclusiveOwnerThread()) {//當(dāng)前線程已持有鎖,重入
      int nextc = c + acquires;//state+1
      if (nextc < 0)
          throw new Error("Maximum lock count exceeded");
      setState(nextc);//已持有鎖,直接設(shè)置state值
      return true;
  }
  return false;
}

解鎖

//解鎖,ReentrantLock方法
public void unlock() {
  sync.release(1);//AQS方法
}
//AQS解鎖
public final boolean release(int arg) {
  if (tryRelease(arg)) {//嘗試解鎖
      Node h = head;
      if (h != null && h.waitStatus != 0)//waitStatus=0時(shí)不進(jìn)行unpark(喚醒),next線程可能中斷
          unparkSuccessor(h);//喚醒隊(duì)列中的線程去獲取鎖
      return true;
  }
  return false;
}
//嘗試解鎖ReentrantLock內(nèi)部靜態(tài)類Sync實(shí)現(xiàn)
protected final boolean tryRelease(int releases) {
  int c = getState() - releases;//state-1
  if (Thread.currentThread() != getExclusiveOwnerThread())
      throw new IllegalMonitorStateException();//非持有鎖的線程進(jìn)行釋放,非法操作
  boolean free = false;
  if (c == 0) {//持有鎖線程全部釋放
      free = true;
      setExclusiveOwnerThread(null);//持有鎖線程置空
  }
  setState(c);//持有鎖線程直接設(shè)置state
  return free;
}

非公平鎖的實(shí)現(xiàn)

非公平鎖和公平鎖的核心區(qū)別是在嘗試獲取鎖方法tryAcquire實(shí)現(xiàn)中沒(méi)有判斷hasQueuedPredecessors()是否需要排隊(duì),其他邏輯和公平鎖是一致的。

以上就是ReentrantLock可重入鎖原理解析的詳細(xì)內(nèi)容,更多關(guān)于ReentrantLock可重入鎖的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論