在複雜任務中,線程可能深陷多層方法調用或遞歸。本文通過一個遞歸文件搜尋案例,深入講解如何利用 InterruptedException 實現響應式線程中斷。
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;
}
// ...
}
@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());
}
}
}
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();
}
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();
}
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(); // 發送中斷信號
}
autoexec.bat,打印絕對路徑。interrupt(),設置中斷標誌。Thread.interrupted() 檢查時拋出異常。run() 被捕獲,打印中斷日誌,線程結束。InterruptedException 後,若無法繼續執行,應重新設置中斷標誌(Thread.currentThread().interrupt())或向上拋出。