掌握線程控制方法是編寫健壯並發程序的前提。本文通過五個核心 API(sleep、join、yield、setDaemon、interrupt)的原理、代碼示例與注意事項,幫助開發者精準控制線程生命周期與協作。
Thread.sleep(millis)InterruptedException 需捕獲public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(getName() + ":" + i);
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
}
}
join()t1.start();
try { t1.join(); } catch (InterruptedException e) { e.printStackTrace(); }
t2.start(); t3.start(); // t2/t3 在 t1 結束後才啟動
Thread.yield()setDaemon(true)start() 前調用Thread t = new Thread(() -> { while(true) { /* 監控邏輯 */ } });
t.setDaemon(true); // 標記為守護線程
t.start();
interrupt() vs stop()| 方法 | 狀態 | 機制 | 推薦度 |
|---|---|---|---|
stop() | 已棄用 | 強制殺死,釋放所有鎖,數據易損壞 | ❌ 禁止 |
interrupt() | 標準 | 設置中斷標誌;阻塞方法拋出 InterruptedException | ✅ 推薦 |
// 正確中斷模式
public void run() {
try {
Thread.sleep(10000); // 可被中斷的阻塞點
} catch (InterruptedException e) {
System.out.println("線程被中斷,安全退出");
return; // 或拋出異常向上傳播
}
}
// 主線程中斷
thread.start();
Thread.sleep(3000);
thread.interrupt(); // 設置中斷標誌,喚醒 sleep
interrupt() 協作式取消,避免 stop()InterruptedException 後:要么清理資源返回,要么重新設置中斷標誌 Thread.currentThread().interrupt()