AQS除了提供上面两个方法外,还提供了一个增强版的方法:tryAcquireNanos(int arg,long nanos)。该方法为acquireInterruptibly方法的进一步增强,它除了响应中断外,还有超时控制。即如果当前线程没有在指定时间内获取同步状态,则会返回false,否则返回true。如下:

    1. public final boolean tryAcquireNanos(int arg, long nanosTimeout)
    2. throws InterruptedException {
    3. if (Thread.interrupted())
    4. throw new InterruptedException();
    5. return tryAcquire(arg) ||
    6. doAcquireNanos(arg, nanosTimeout);
    7. }
    1. private boolean doAcquireNanos(int arg, long nanosTimeout)
    2. throws InterruptedException {
    3. //如果nanosTimeout小于0直接返回
    4. if (nanosTimeout <= 0L)
    5. return false;
    6. //通过将当前时间+设置的超时时间=超时的时间点
    7. final long deadline = System.nanoTime() + nanosTimeout;
    8. final Node node = addWaiter(Node.EXCLUSIVE);
    9. boolean failed = true;
    10. try {
    11. for (; ; ) {
    12. final Node p = node.predecessor();
    13. if (p == head && tryAcquire(arg)) {
    14. setHead(node);
    15. p.next = null; // help GC
    16. failed = false;
    17. return true;
    18. }
    19. //超时时间点-当前时间=剩余的超时时间
    20. nanosTimeout = deadline - System.nanoTime();
    21. //如果剩余的超时时间小于0说明已超时,则返回
    22. if (nanosTimeout <= 0L)
    23. return false;
    24. //如果没有超时则等待nanosTimeout纳秒
    25. //注:该线程会直接从LockSupport.parkNanos(this, nanosTimeout)中返回
    26. //LockSupport是JUC提供的一个阻塞和唤醒的工具类
    27. if (shouldParkAfterFailedAcquire(p, node) &&
    28. //如果nanosTimeout大于spinForTimeoutThreshold,就需要休眠nanosTimeout
    29. nanosTimeout > spinForTimeoutThreshold)
    30. LockSupport.parkNanos(this, nanosTimeout);
    31. //如果nanosTimeout小于等于spinForTimeoutThreshold,那么就不需要休眠了,直接进入快速自旋
    32. // 因为spinForTimeoutThreshold已经很短了,如果在更短的超时时间内还要休眠,可能会导致超时时间不那么准确
    33. //线程的状态切换是需要时间的
    34. //判断线程是否已经被中断了
    35. if (Thread.interrupted())
    36. throw new InterruptedException();
    37. }
    38. } finally {
    39. if (failed)
    40. cancelAcquire(node);
    41. }
    42. }

    与独占式获取锁响应中断的不同就在加入到同步队列之后对超时时间的计算
    image.png