假设以下代码使用调试器执行,以便我们可以预测执行顺序。
- t1 -- 这里 task1 开始处理一些长任务。
- t2 --- task2 被阻塞 @ Syncronized 语句,因为 task1 持有锁。
- t3 - task2 被中断但它错过了,因为 task2 正在使用内部锁,因此不能在@同步时被中断。(Renenterant.lockInterruptible() 会抛出 InterruptedExecption)。
- t4 --- task1 被中断。然而,尽管在 try catch 块中执行了复杂的任务,但从未抛出 InterruptedExecption。这是为什么 ?
代码:
public class TestInteruptibility {
public static Object lock = new Object();
public static boolean spin = true;
public static void main(String[] args) {
Thread task1 = new Thread(new Task(), "Task1");
Thread task2 = new Thread(new Task(), "Task2");
Thread notifier1 = new Thread(new Notifier(), "Notifier1");
task1.start();
task2.start();
task2.interrupt();
task1.interrupt();
notifier1.start();
}
}
class Task implements Runnable {
public void run() {
synchronized (TestInteruptibility.lock) {
System.out.println("Performing Long Task");
try {
while (TestInteruptibility.spin) {
}
System.out.println("Finsihed Performing Long Task");
TestInteruptibility.lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("I got interrupted while i was waiting @ wait()");
}
System.out.println("Ending Task");
}
}
}
class Notifier implements Runnable {
public void run() {
synchronized (TestInteruptibility.lock) {
System.out.println("Performing notification");
TestInteruptibility.lock.notify();
System.out.println("Ending notification");
}
}
}