AQS中有acquire方法:
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
上面的acquire方法用在ReentrantLock.FairSync,ReentrantLock.NonfairSync,ReentrantReadWriteLock.WriteLock,ThreadPoolExecutor.Worker类中的lock方法,加锁过程中如果失败就会进入队列(可能一开始就在队列)反复阻塞被唤醒直到成功获取锁,在此过程中,线程可能面临中断,acquireQueued方法返回值就是在等待的过程中是否被中断,该方法应用在await(),awaitNanos(long),awaitUnti(date),await(long,TimeUnit),awaitUninterruptibly()方法中用以判断中断状态
下面是通过代码模拟线程抢锁等待过程被中断
public static void main(String[] args) throws InterruptedException {
Lock lock = new ReentrantLock();
new Thread(() -> {
try {
lock.lock();
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}).start();
Thread.sleep(100);
Thread thread1 = new Thread(() -> {
try {
lock.lock();
System.out.println(Thread.currentThread().getName() + "=" + Thread.currentThread().isInterrupted());
} finally {
lock.unlock();
}
});
Thread thread2 = new Thread(() -> {
lock.lock();
try {
System.out.println(Thread.currentThread().getName() + "=" + Thread.currentThread().isInterrupted());
} finally {
lock.unlock();
}
});
thread1.start();
Thread.sleep(1);
thread2.start();
Thread.sleep(1);
thread2.interrupt();
}
执行上面的代码,thread2直接进入断点interrupted=true