ReentrantLock通过unlock方法调用公平锁的unlock方法
public final boolean release(int arg) {
//尝试释放锁,如果释放成功,则status置为了0,exclusiveOwnerThread置为了null
if (tryRelease(arg)) {
Node h = head;
//持有锁的线程释放锁后,需要叫醒在队列中等待的线程,如果头节点不为空,且状态不为0,进行unpark
//头结点为空的话,说明队列是空的,没有线程要叫醒,而之所以要waitStatus不为0才unpark,是因为waitStatus=0时,表明head就是队列里的最后一个节点,没有需要唤醒的线程了(如果它后面还有等待线程,则它的waitStatus=-1)。
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;
//如果status-1=0,可以释放锁
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
//更新status
//释放锁,更新为0
//重入锁释放一次锁,更新为status-1
setState(c);
return free;
}
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;
//将头节点的waitStatus更新为0
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;
//一般情况下,待唤醒线程是下一个节点,但如果下一个节点线程被中断取消或者是null,就不是要被唤醒线程
//从后往前遍历的原因是:在加锁的入队操作里,先通过CAS设置了tail,如果在设置完tail后线程切换,则tail.pre是有节点的,但tail.pre.next=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);
}