假設下面的代碼是通過調試器執行的,以便我們可以預測執行的順序。爲什麼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