实例背景
如果线程实现了复杂的算法并且分布在几个方法中,或者线程里面有递归调用的方法,这样的话,就得需要使用一个更好的机制来控制线程的中断。为了达到这个目的,java 提供了 InterruptedException异常,当检查到线程中断的时候,就抛出这个异常,然后在 run()方法 中捕获 并处理这个异常。
示例:线程类实现 在一个文件夹及其子文件夹中寻找一个指定的文件。
import java.io.File;
/**
* 中断控制 - run方法中 通过捕获 InterruptedException 异常来控制 线程是否中断
*/
public class FileSearch implements Runnable{
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);
try {
if(file.isDirectory()){
directoryProcess(file);
}
} catch (InterruptedException e) { // 通过 run 方法来 捕获 InterruptedException 来判断是否被中断.
System.out.println(Thread.currentThread().getName() + " 被中断...");
}
}
// 目录操作
public void directoryProcess(File file) throws InterruptedException{
File[] list = file.listFiles();
if(list != null && list.length > 0){
for(int i=0;i<list.length;i++){
if(list[i].isDirectory()){ // 目录
directoryProcess(list[i]);
}else{ // 文件
fileProcess(list[i]);
}
}
}
}
// 文件操作
public void fileProcess(File file) throws InterruptedException{
if(fileName.equals(file.getName())){
System.out.println(Thread.currentThread().getName()+",文件名:"+file.getName()+",路径:"+file.getAbsolutePath() +",找到了..");
}else{
System.out.println("【fileName】-" + fileName +",【file.getName】-"+file.getName() +",没被找到..");
}
if(Thread.interrupted()){ //判断 线程是否被中断
throw new InterruptedException();
}
}
}
public class FileSearchTest {
public static void main(String[] args) {
FileSearch fileSearch = new FileSearch("F:\\logs", "warn.log");
Thread thread = new Thread(fileSearch);
thread.start();
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
}
}
// console结果:
【fileName】-warn.log,【file.getName】-log4j.properties,没被找到..
Thread-0 被中断...