d().getName() + "睡了5秒");
} catch (Exception e) {
System.out.println(Thread.currentThread().getName() + "runnable exception:" + e);
} finally {
lock.unlock();
}
System.out.println(Thread.currentThread().getName() + " over");
}
}
执行结果为:
main start
Thread-0runnable run
Thread-0开始睡眠
main end
Thread-1runnable run
Thread-0睡了5秒
Thread-0 over
Thread-1开始睡眠
Thread-1runnable exception:java.lang.InterruptedException: sleep interrupted
Thread-1 over
可以看到中断了并没有对获取锁产生影响,最后是sleep方法响应的中断。
下面是我在本地模拟的lockInterruptibly()阻塞中断:
public class ReentrantLockInterruptableDemo {
public static void main(String[] args) throws InterruptedException {
System.out.println("main start");
Thread thread1 = new Thread(new LockThreadInterruptableDemo());
Thread thread2 = new Thread(new LockThreadInterruptableDemo());
thread1.start();
Thread.sleep(1000); // 确保thread1获取到了锁
thread2.start(); // 此时thread2处于获取锁的阻塞状态
thread2.interrupt();
System.out.println("main end");
}
}
class LockThreadInterruptableDemo implements Runnable {
public static ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "runnable run");
try {
lock.lockInterruptibly();
System.out.println(Thread.currentThread().getName() + "开始睡眠");
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName() + "睡了5秒");
} catch (Exception e) {
System.out.println(Thread.currentThread().getName() + "runnable exception:" + e);
} finally {
try {
lock.unlock();
} catch (IllegalMonitorStateException e) {
System.out.println("因线程" + Thread.currentThread().getName() + "提前中断导致未获取到锁");
}
}
System.out.println(Thread.currentThread().getName() + " over");
}
}
结果为:
main start
Thread-0runnable run
Thread-0开始睡眠
main end
Thread-1runnable run
Thread-1runnable exception:java.lang.InterruptedException
因线程Thread-1提前中断导致未获取到锁
Thread-1 over
Thread-0睡了5秒
Thread-0 over
结束语
对于线程中断的处理比较常见,尤其是涉及到多线程的框架、组件中。而能否处理好线程中断的各种情况,则体现出一个程序员对多线程掌握的熟练情况。