上一问https://coding.imooc.com/learn/questiondetail/146107.html
上一问中老师说“必须要等到被唤醒后,并且拿到锁之后才能响应中断的,wait期间什么都做不了”。我下面的代码为什么可以响应中断。
public class WaitingStatusToInterrupt {
private static Object resourceA = new Object();
static class Thread1 extends Thread {
@Override
public void run() {
synchronized (resourceA) {
System.out.println(Thread.currentThread().getName() + "--获取到resourceA锁");
try {
System.out.println(Thread.currentThread().getName() + "--释放resourceA锁");
resourceA.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "--再次获取到resourceA锁");
}
}
}
static class Thread2 extends Thread {
@Override
public void run() {
synchronized (resourceA) {
System.out.println(Thread.currentThread().getName() + "--获取到resourceA锁");
resourceA.notify();
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread1 thread1 = new Thread1();
thread1.start();
Thread.sleep(1000);
System.out.println("----------------------");
System.out.println(thread1.getName() + "--" + thread1.getState());
thread1.interrupt();
Thread.sleep(1000);
System.out.println("----------------------");
Thread2 thread2 = new Thread2();
thread2.start();
Thread.sleep(1000);
}
运行结果:
Thread-0--获取到resourceA锁
Thread-0--释放resourceA锁
java.lang.InterruptedException
----------------------
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:502)
Thread-0--WAITING
at com.lzp.java.concurrent.threadcore.threadandobject.object.WaitingStatusToInterrupt$Thread1.run(WaitingStatusToInterrupt.java:17)
Thread-0--再次获取到resourceA锁
----------------------
Thread-1--获取到resourceA锁