package com.jackson.deng.concurrent.chapter1.four;
import java.io.File;
import java.util.concurrent.TimeUnit;
/**
* 簡意爲:在指定路徑下找到指定文件,如果10秒沒有找到,就打斷這個文件搜索的線程.<br>
* 應用場景:<br>
* 接收郵件的時候,如果超過指定時間沒有接收到,給出不響應的消息
*
* @author jackson
*
*/
public class FileSearchThreadInterrupt {
public class FileSearch extends Thread {
private String initPath;
private String fileName;
public FileSearch(String initPath, String fileName) {
this.initPath = initPath;
this.fileName = fileName;
}
@Override
public void run() {
File file = new File(initPath);
if (file.isDirectory()) {
try {
directoryProcess(file);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void directoryProcess(File file) throws InterruptedException {
File[] listFiles = file.listFiles();
if (listFiles != null) {
for (File f : listFiles) {
if (f.isDirectory()) {
directoryProcess(f);
} else {
fileProcess(f);
}
}
}
}
private void fileProcess(File file) throws InterruptedException {
if (file.getName().equals(fileName)) {
System.out.println(Thread.currentThread().getName() + " : " + file.getAbsolutePath());
Thread.currentThread().stop();
}
if (isInterrupted()) {
throw new InterruptedException();
}
}
}
public static void main(String[] args) {
FileSearchThreadInterrupt fsti = new FileSearchThreadInterrupt();
Thread task = fsti.new FileSearch("c:\\", "autoexec.bat");
task.start();
try {
TimeUnit.SECONDS.sleep(10);
task.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
代碼挺簡單的,就不多做解釋了..給出找到和沒找到的運行結果
下面是找到了的