首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 併發編程實例(四):掌握線程中斷的藝術

     編輯:Java 相關知識

引言

在複雜任務中,線程可能深陷多層方法調用或遞歸。本文通過一個遞歸文件搜尋案例,深入講解如何利用 InterruptedException 實現響應式線程中斷。

實現步驟

步驟 1:定義任務類實現 Runnable

public class FileSearch implements Runnable {
    private final String initPath;
    private final String fileName;

    public FileSearch(String initPath, String fileName) {
        this.initPath = initPath;
        this.fileName = fileName;
    }
    // ...
}

步驟 2:實現 run() 方法,捕獲中斷異常

@Override
public void run() {
    File root = new File(initPath);
    if (root.isDirectory()) {
        try {
            directoryProcess(root);
        } catch (InterruptedException e) {
            System.out.printf("%s: 搜尋已中斷%n", Thread.currentThread().getName());
        }
    }
}

步驟 3:遞歸處理目錄,檢查中斷標誌

private void directoryProcess(File file) throws InterruptedException {
    File[] files = file.listFiles();
    if (files != null) {
        for (File f : files) {
            if (f.isDirectory()) {
                directoryProcess(f);
            } else {
                fileProcess(f);
            }
        }
    }
    if (Thread.interrupted()) throw new InterruptedException();
}

步驟 4:處理單個文件,同樣檢查中斷

private void fileProcess(File file) throws InterruptedException {
    if (file.getName().equals(fileName)) {
        System.out.printf("%s : %s%n", Thread.currentThread().getName(), file.getAbsolutePath());
    }
    if (Thread.interrupted()) throw new InterruptedException();
}

步驟 5:主程序啟動線程並定時中斷

public static void main(String[] args) throws InterruptedException {
    FileSearch task = new FileSearch("C:\\", "autoexec.bat");
    Thread t = new Thread(task);
    t.start();
    TimeUnit.SECONDS.sleep(10);
    t.interrupt(); // 發送中斷信號
}

執行流程解析

  1. 線程啟動,遞歸遍歷 C 盤目錄。
  2. 若找到 autoexec.bat,打印絕對路徑。
  3. 10 秒後主線程調用 interrupt(),設置中斷標誌。
  4. 工作線程在下一次 Thread.interrupted() 檢查時拋出異常。
  5. 異常層層冒泡至 run() 被捕獲,打印中斷日誌,線程結束。

最佳實踐總結

  • 頻繁檢查:在長時間循環、遞歸、阻塞操作前後檢查中斷標誌。
  • 拋出而非吞噬:捕獲 InterruptedException 後,若無法繼續執行,應重新設置中斷標誌(Thread.currentThread().interrupt())或向上拋出。
  • 文檔化中斷策略:在方法 JavaDoc 中說明是否響應中斷、如何響應。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved