先看一段 Java 程式碼:
public class Z
{
public static void main(String[] args)
{
new Z();
}
private Z()
{
Z a1 = this;
Z a2 = this;
synchronized(a1)
{
try
{
a2.wait();
System.out.println("done waiting");
}
catch (InterruptedException e) { System.out.println("InterruptedException"); }
catch (Exception e) { System.out.println("Exception"); }
finally { System.out.println("finally"); }
}
System.out.println("all done");
}
}
編譯後執行 java Z,結果完全沒有輸出,程式也不會結束。用 ps 一看,狀態是 sl+。
D 不可中斷的睡眠(通常是 IO)
R 正在執行或於執行佇列中
S 休眠狀態
T 停止或被追蹤
Z 僵屍進程
W 進入記憶體交換(自核心 2.6 起失效)
X 已死亡的進程
< 高優先級
N 低優先級
L 部分頁面被鎖進記憶體
s 含子進程
+ 位於前景的進程組
l 多執行緒(clone 出來的線程)
對照可知:這個程式處於休眠狀態、多執行緒,且屬於前景進程組。
Java 中三個方法的行為是:wait() 讓線程進入等待並釋放鎖,把自己存入線程池;notify() 通常喚醒池中的第一個;notifyAll() 喚醒池中全部等待線程。
範例中的程式呼叫 wait() 之後就一直在等別人 notify,而全程式只有一個線程,自然永遠等不到,於是就停在休眠狀態——這也正是 ps 顯示 sl+ 的由來。