在独占模式下释放锁
public final boolean release(int arg) {
// 如果释放锁成功,则唤醒head节点后边的节点
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return false;
}
protected boolean tryRelease(int arg) {
throw new UnsupportedOperationException();
}
private void unparkSuccessor(Node node) {
// 如果节点的waitStatus是负数则清0
int ws = node.waitStatus;
if (ws < 0)
compareAndSetWaitStatus(node, ws, 0);
// 唤醒当前节点后面的节点,如果后面的节点是取消状态那么从后往前找一个非取消状态的节点
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);
}
和tryAcquire一样,tryRelease也需要子类去实现