Java 多線程開發中,如何優雅、安全地停止線程是核心必修課。早期 Thread.stop()、suspend()、resume() 已被棄用(JDK 1.2+),因會導致鎖釋放不完整、資料不一致、死鎖風險。現代標準做法:中斷機制 + 狀態標誌位 + 協作式停止。
stop():強制拋出 ThreadDeath 錯誤,釋放所有鎖,導致受保護資料處於不一致狀態,其他線程讀取損壞資料suspend():線程持有鎖時被掛起,其他線程嘗試獲取同一鎖將永久阻塞 → 死鎖resume():若先於 suspend 執行,線程永久掛起參考 Sun 官方文檔:《Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?》
public class WorkerThread extends Thread {
private volatile boolean running = true;
@Override
public void run() {
try {
while (running && !Thread.currentThread().isInterrupted()) {
// 執行業務邏輯
// 定期檢查中斷狀態
if (Thread.interrupted()) { // 清除中斷狀態
throw new InterruptedException("Thread interrupted");
}
// 或阻塞操作可拋出 InterruptedException
Thread.sleep(1000);
}
} catch (InterruptedException e) {
// 執行清理工作:關閉資源、釋放鎖、記錄日誌
Thread.currentThread().interrupt(); // 重新設置中斷狀態供上層感知
} finally {
// 確保資源釋放
}
}
public void requestStop() {
running = false;
interrupt(); // 打斷阻塞操作
}
}
volatile boolean running:保證跨線程可見性,非阻塞輪詢檢查interrupt():設置中斷標誌;若線程處於阻塞(sleep/wait/join/I/O),拋出 InterruptedExceptionThread.interrupted():檢查並清除中斷標誌;isInterrupted():僅檢查不清除InterruptedException 後,必須重新設置中斷標誌(Thread.currentThread().interrupt()),避免吞噬中斷信號傳統阻塞 I/O(InputStream.read()、ServerSocket.accept())在不同平台對中斷反應不一:
InterruptedIOException / ClosedByInterruptExceptionIOExceptionInterruptibleChannel 實現類(FileChannel、SocketChannel、Selector)原生支援中斷,拋出 ClosedByInterruptException// NIO 範例
Selector selector = Selector.open();
SocketChannel channel = SocketChannel.open();
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_READ);
// 停止時
selector.wakeup(); // 使 select() 返回
channel.close(); // 觸發 ClosedByInterruptException
stop()/suspend()/resume()/destroy()shutdown()/cancel() 方法,內部調用 interrupt() + 設置標誌位Thread.currentThread().isInterrupted() 或 running 標誌InterruptedException 後執行清理並重新設置中斷java.util.concurrent 高階組件:ExecutorService.shutdownNow()、Future.cancel(true)、CompletableFuture、ThreadPoolExecutorExecutorService.shutdownNow():嘗試中斷所有執行中任務,返回未完成任務列表Future.cancel(true):若任務正在執行,調用 interrupt()Lock.lockInterruptibly():可中斷的鎖獲取BlockingQueue:take()/put() 可中斷採用協作式中斷模式,編寫健壯、可維護的多線程程式,是 Java 開發者的專業標誌。