AQS除了提供上面两个方法外,还提供了一个增强版的方法:tryAcquireNanos(int arg,long nanos)。该方法为acquireInterruptibly方法的进一步增强,它除了响应中断外,还有超时控制。即如果当前线程没有在指定时间内获取同步状态,则会返回false,否则返回true。如下:
public final boolean tryAcquireNanos(int arg, long nanosTimeout)throws InterruptedException {if (Thread.interrupted())throw new InterruptedException();return tryAcquire(arg) ||doAcquireNanos(arg, nanosTimeout);}
private boolean doAcquireNanos(int arg, long nanosTimeout)throws InterruptedException {//如果nanosTimeout小于0直接返回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 GCfailed = false;return true;}//超时时间点-当前时间=剩余的超时时间nanosTimeout = deadline - System.nanoTime();//如果剩余的超时时间小于0说明已超时,则返回if (nanosTimeout <= 0L)return false;//如果没有超时则等待nanosTimeout纳秒//注:该线程会直接从LockSupport.parkNanos(this, nanosTimeout)中返回//LockSupport是JUC提供的一个阻塞和唤醒的工具类if (shouldParkAfterFailedAcquire(p, node) &&//如果nanosTimeout大于spinForTimeoutThreshold,就需要休眠nanosTimeoutnanosTimeout > spinForTimeoutThreshold)LockSupport.parkNanos(this, nanosTimeout);//如果nanosTimeout小于等于spinForTimeoutThreshold,那么就不需要休眠了,直接进入快速自旋// 因为spinForTimeoutThreshold已经很短了,如果在更短的超时时间内还要休眠,可能会导致超时时间不那么准确//线程的状态切换是需要时间的//判断线程是否已经被中断了if (Thread.interrupted())throw new InterruptedException();}} finally {if (failed)cancelAcquire(node);}}
与独占式获取锁响应中断的不同就在加入到同步队列之后对超时时间的计算
