AQS提供了acquire(int arg)方法以供独占式获取同步状态,但是该方法对中断不响应,对线程进行中断操作后,该线程会依然位于CLH同步队列中等待着获取同步状态。为了响应中断,AQS提供了acquireInterruptibly(int arg)方法,该方法在等待获取同步状态时,如果当前线程被中断了,会立刻响应中断抛出异常InterruptedException。

    1. //模板方法,独占式获取锁(同步状态)响应中断
    2. public final void acquireInterruptibly(int arg)
    3. throws InterruptedException {
    4. //判断是否被中断
    5. if (Thread.interrupted())
    6. throw new InterruptedException();
    7. if (!tryAcquire(arg))
    8. doAcquireInterruptibly(arg);
    9. }


    1. private void doAcquireInterruptibly(int arg)
    2. throws InterruptedException {
    3. final Node node = addWaiter(Node.EXCLUSIVE);
    4. boolean failed = true;
    5. try {
    6. for (; ; ) {
    7. final Node p = node.predecessor();
    8. if (p == head && tryAcquire(arg)) {
    9. setHead(node);
    10. p.next = null; // help GC
    11. failed = false;
    12. return;
    13. }
    14. if (shouldParkAfterFailedAcquire(p, node) &&
    15. parkAndCheckInterrupt())
    16. //与acquireQueued唯一的区别就是这里,如果中断了就抛出异常
    17. throw new InterruptedException();
    18. }
    19. } finally {
    20. if (failed)
    21. cancelAcquire(node);
    22. }
    23. }