Read the unlock() source code of ReentrantLock: //This method: delegate to the release implementation of sync. public void unlock() { sync.release(1); } public final boolean release(int arg) { // release the lock successfully if (tryRelease(arg)) { Node h = head; if (h != null && h.waitStatus != 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, that is, getState is 1, if c!=0, it means the lock is reentrant. if (c == 0) { free = true; setExclusiveOwnerThread(null); } setState(c); return free; } // wake up the second node private void unparkSuccessor(Node node) { int ws = node.waitStatus; if (ws < 0) //Set the first node state to 0 compareAndSetWaitStatus(node, ws, 0); // get the second node Node s = node.next; if (s == null || s.waitStatus > 0) { s = null; //Start the loop from the end of the queue until you get the node with the state < 0 closest to the note for (Node t = tail; t != null && t != node; t = t.prev) if (t.waitStatus <= 0) s = t; } //Unlock and wake up a waiting thread if (s != null) LockSupport.unpark(s.thread); }
The unlock method of ReentrantLockd realizes source code analysis
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=326523862&siteId=291194637
Recommended
Ranking