線程從創建到消亡的完整生命周期管理,是併發編程的基礎功力。
new Thread() 創建start() 啟動,進入就緒隊列run()run() 正常返回或異常退出isAlive():STARTED 且未 TERMINATED 返回 true。
private volatile boolean done = false;
public void run() {
while (!done) {
nextCharacter();
try { Thread.sleep(getPauseTime()); }
catch (InterruptedException ie) { return; }
}
}
public void setDone() { done = true; }
缺點:輪詢延遲(最長等待 sleep 時間)。
public void run() {
while (!Thread.currentThread().isInterrupted()) {
nextCharacter();
try { Thread.sleep(getPauseTime()); }
catch (InterruptedException ie) { return; } // 異常即清除中斷狀態
}
}
public void stopThread() { thread.interrupt(); }
interrupt() 兩大效果:
sleep/wait/join)拋出 InterruptedException 並清除中斷標記isInterrupted() 檢查)優勢:響應更及時,無需輪詢間隔。
suspend()/resume() 已廢棄(死鎖風險)sleep():僅影響當前線程,非真正掛起wait()/notify() 或 Condition.await()/signal() 實現外部可控掛起恢復thread.join(); // 阻塞直到 run() 結束 thread.join(5000); // 超時版本
風險:首次調用可能長時間阻塞,生產環境常用 isAlive() 輪詢或 Future 模式。
public void run() {
while (!Thread.currentThread().isInterrupted()) { /* ... */ }
}
任務未綁定線程時,通過 Thread.currentThread() 獲取當前執行線程引用。
setDaemon(true):JVM 僅剩守護線程時自動退出。適合後台服務(GC、監控)。