ReentrantLock原始碼解析( 釋放公平鎖)
阿新 • • 發佈:2019-01-04
1、unlock()
public void unlock() {
sync.release(1);
}
unlock()呼叫的release()方法,方法中引數傳入1。跟獲取鎖一樣,每呼叫一次unlock(),鎖的狀態減1,當鎖的狀態等於0時,將會喚醒佇列中的下一個節點。
2、release()
3、tryRelease()public final boolean release(int arg) { if (tryRelease(arg)) {//釋放鎖,如果鎖的狀態為0時,返回true Node h = head; if (h != null && h.waitStatus != 0)//如果鎖狀態為0時,喚醒下一個節點 unparkSuccessor(h); return true; } return false; }
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、unparkSuccessor():喚醒下一個執行緒
private void unparkSuccessor(Node node) { /* * If status is negative (i.e., possibly needing signal) try * to clear in anticipation of signalling. It is OK if this * fails or if status is changed by waiting thread. */ int ws = node.waitStatus; if (ws < 0) compareAndSetWaitStatus(node, ws, 0); /* * Thread to unpark is held in successor, which is normally * just the next node. But if cancelled or apparently null, * traverse backwards from tail to find the actual * non-cancelled successor. */ Node s = node.next;//頭節點的下一個節點 if (s == null || s.waitStatus > 0) {//如果頭節點的下一個節點為空或者已經取消 s = null; for (Node t = tail; t != null && t != node; t = t.prev)//從尾節點往前迴圈查詢最靠近頭節點且狀態為SINGLE的節點 if (t.waitStatus <= 0) s = t; } if (s != null) LockSupport.unpark(s.thread);//喚醒節點 }