代碼驗證
public class SleepDemo extends Thread {
public void run() {
for (int i = 0; i < 5; i++)
System.out.println(getName() + ": " + i);
}
public static void main(String[] args) throws InterruptedException {
SleepDemo a = new SleepDemo();
SleepDemo b = new SleepDemo();
a.start();
Thread.sleep(10); // 當前線程 = main
b.start();
System.out.println("睡醒的線程: " + Thread.currentThread().getName()); // 輸出 main
}
}
核心結論
Thread.sleep() 是 靜態方法,作用於調用該方法的當前線程。
- 主線程調用 → 主線程睡眠;子線程調用 → 子線程睡眠。
- 不釋放鎖(同步塊/方法持有的 monitor),需用
wait() 釋放鎖並進入等待隊列。
最佳實踐
- 捕獲
InterruptedException 並恢復中斷狀態:Thread.currentThread().interrupt();。
- 避免在持有鎖時睡眠,導致其他線程饑餓。
- 定時任務優先使用
ScheduledExecutorService 而非 sleep 循環。