先確認兩件事:執行緒的執行體是 run() 裡的每一行;Thread.sleep() 的作用是讓當前執行緒睡眠。
當某個執行緒的 suspend() 被呼叫,它會被掛起。關鍵在於:掛起時它不會釋放已經持有的鎖。這正是它被判定為過時方法的原因,下面的例子會直接展示這個陷阱如何把整個程式卡死。
public class MyThread extends Thread {
private long i = 0;
public long getI() { return i; }
public void setI(long i) { this.i = i; }
@Override
public void run() {
while (true) {
i++;
System.out.println(i); // 注意:這是同步方法
}
}
}
public class Run {
public static void main(String[] args) {
try {
MyThread thread = new MyThread();
thread.start(); // 啟動 thread
Thread.sleep(1000); // 讓 main 睡眠,thread 有機會執行
thread.suspend(); // 掛起 thread
System.out.println("main end!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
流程是這樣的:main 睡 1 秒,這段時間 thread 有機會拿到 CPU 並開始印 i;1 秒後 main 醒來,把 thread 掛起,thread 不再印數字;接著 main 要印 "main end!"。
但這行永遠印不出來。原因在 System.out.println(Object) 的實作:
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) { // 必須先取得 PrintStream 的鎖
print(s);
newLine();
}
}
thread 被掛起時,它的 run() 正卡在 println 的 synchronized 區塊裡,因此持有 PrintStream 的鎖不放。main 要印字就得搶同一把鎖,於是永久等待。而 System.out 是 System 類中的唯一靜態實例:
public final static PrintStream out = null;
全 JVM 共用一個,逃無可逃。這就是 suspend() 的致命缺陷:它製造了一種「持有鎖卻永久不前進」的僵局,而且沒有任何超時或中斷能解開。
resume() 的功能很單純:恢復被 suspend() 掛起的執行緒,讓它重新有機會取得 CPU。但因為 suspend() 本身不安全,resume() 自然也一起被標記為過時。
現行的標準做法是用一個旗標變數搭配 wait() / notify():request 端把旗標設為 true 並 notify,工作執行緒在迴圈中檢查旗標,若為 true 就 wait() 讓出執行權——而且 wait() 會釋放鎖,不會有 deadlock 風險;恢復時再把旗標設回 false 並 notifyAll。關鍵差別就在「等待時是否釋放鎖」這一點上。