Thread.stop()、suspend()、resume()、runFinalizersOnExit() **極度不安全**,已棄用,**嚴禁使用**。
run() 方法自然結束,線程自動終止。
volatile boolean finished = false;
public void run() {
while (!finished) {
doWork();
try { Thread.sleep(10000); }
catch (InterruptedException e) { break; } // 也可作為中斷點
}
}
// 外部呼叫
public void shutdown() { finished = true; }
關鍵點:volatile 保證可見性;sleep 期間拋出 InterruptedException 亦可跳出。
public void run() {
try {
while (true) {
// BlockingQueue.take() 會阻塞
Response msg = queue.take();
process(msg);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // 重設中斷狀態(良好習慣)
// 或直接 break/return
}
}
// 外部終止
thread.interrupt(); // 使 queue.take() 拋出 InterruptedException
原理:interrupt() 設定線程中斷狀態;標準阻塞方法(sleep、wait、join、BlockingQueue、Selector、Channel 等)檢測到中斷即拋出 InterruptedException,給代碼機會清理並退出。
ExecutorService + Future.cancel(true) 管理生命週期。InterruptedException 後,**務必重設中斷旗標**(Thread.currentThread().interrupt())或拋出,避免吞噬中斷信號。volatile boolean 標誌;阻塞調用依賴 interrupt()。stop()/suspend()/resume()。