public void unlock() {
sync.release(1);
}
ReentrantLock
释放锁实际上是调用AbstractQueuedSynchronizer
的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;
}
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;
}
每释放一次锁,就会把state
(锁的状态)减1,直到state
等于0,锁被完全释放,该方法就会返回true
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)
if (t.waitStatus <= 0)
s = t;
}
if (s != null)
LockSupport.unpark(s.thread);
}
获取当前线程节点的后置节点,如果后置节点不为空且状态为阻塞,则唤醒后置节点线程,如果后置节点为空或者状态不是阻塞,就从队列的尾节点,从后往前找离当前线程节点最近且状态被阻塞的节点,并唤醒它