p; parkAndCheckInterrupt())
//被唤醒后检查到被中断时抛出中断异常
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
响应中断的获取同步状态被中断时会直接抛出中断异常,而不响应的是自己中断
响应超时
响应超时的获取同步状态使用tryAcquireNanos
超时时间为纳秒级别
public final boolean tryAcquireNanos(int arg, long nanosTimeout)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
return tryAcquire(arg) ||
doAcquireNanos(arg, nanosTimeout);
}
可以看出响应超时同时也会响应中断
doAcquireNanos
也与原过程类似
private boolean doAcquireNanos(int arg, long nanosTimeout)
throws InterruptedException {
if (nanosTimeout <= 0L)
return false;
final long deadline = System.nanoTime() + nanosTimeout;
final Node node = addWaiter(Node.EXCLUSIVE);
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return true;
}
//还有多久超时
nanosTimeout = deadline - System.nanoTime();
if (nanosTimeout <= 0L)
//已超时
return false;
if (shouldParkAfterFailedAcquire(p, node) &&
//大于1ms
nanosTimeout > spinForTimeoutThreshold)
//超时等待
LockSupport.parkNanos(this, nanosTimeout);
//响应中断
if (Thread.interrupted())
throw new InterruptedException();
}
} finally {
if (failed)
&n