在lock中, 我们有响应中断处理和不响应中断处理的lock, 而在日常使用中, 经常使用的是不响应的.lock操作
本文就来学习一下, 在aqs中是如何做到响应线程interrupt的获取锁操作的
public final void acquireInterruptibly(int arg)
throws InterruptedException {
// 在尝试获取之前判断线程异常状态
// 这里的异常是用户程序处理的, 其实这里个人感觉用isInterrupted也不是不行
if (Thread.interrupted())
throw new InterruptedException();
// 这里就直接尝试获取锁, 不会判断异常标志
if (!tryAcquire(arg))
// 尝试获取锁失败后, 就会进入自旋或者进入队列
doAcquireInterruptibly(arg);
}
这个方法与acquireQueued是十分相似的
可以说唯一的不同之处就在于被unPark之后如果检测到线程的中断标志是true就不会去获得锁
private void doAcquireInterruptibly(int arg)
throws InterruptedException {
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;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
// 被unPark后发现中断标志是true
// 这里会不去获取锁直接抛出异常中断
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
以上就是响应中断的lock
值得一提的是interrupt的时机会决定这个线程是否进入等待队列
如果线程进入了等待队列, 那么你就算interrupt了, 他还是会继续等待, 直到被unPark才会判断线程的终止状态
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[2];
Lock lock = new ReentrantLock();
for (int i = 0; i < threads.length; i ++) {
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
try {
lock.lockInterruptibly();
System.out.println(Thread.currentThread().isInterrupted());
System.out.println(Thread.currentThread().getName() + "开始执行");
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName() + "执行完毕");
} catch(Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
});
}
threads[0].start();
Thread.sleep(1000);
threads[1].start();
threads[1].interrupt();
System.out.println("1");
}
这是我自己测试用的代码, 如果需要测试在park的状态下interrupt的话, 可以在线程1的start下面加一段睡眠时间, 即先让线程进入aqs等待队列再去打终止标志