假设下面的代码是通过调试器执行的,以便我们可以预测执行的顺序。为什么task1线程不会中断
- t1 - 这里task1开始处理一些长时间的任务。
- t2 --- task2被阻止@同步语句,因为task1持有锁。
- t3 - task2被中断但错过了,因为task2正在使用内部锁,因此不能被中断@ synchronized。 (Renenterant.lockInterruptible()会抛出InterruptedExecption)。
- t4 --- task1中断。然而,尽管在try catch块中执行了复杂的任务,但InterruptedExeption从未抛出。这是为什么 ?
代码:
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");
}
}
}
'spin'永远不会是假的,循环永远不会终止,你永远不会看到“Finsihed [sic]正在执行长时间任务”。 – erickson 2013-03-17 06:45:26