标签:
上一个例子中使用的机制,可以使用在线程很容易被中断的情况下。但是如果线程实现了复杂的算法并且分布在几个方法中,或者线程里有递归调用的方法,我们就得使用一个更好的机制来控制线程的中断。为了达到这个目的,Java提供了InterruptedException异常。当检查到线程中断的时候,就抛出这个异常,然后在run()中捕获并处理这个异常。
package concurrency;
import java.io.File;
import java.util.concurrent.TimeUnit;
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);
if(file.isDirectory()) {
try {
directoryProcess(file);
} catch (InterruptedException e) {
System.out.printf("%s: The search has been interrupted",
Thread.currentThread().getName());
}
}
}
private void directoryProcess(File file) throws InterruptedException {
File[] list = file.listFiles();
if(list != null){
for(int i = 0; i < list.length; i++){
if(list[i].isDirectory()){
directoryProcess(list[i]);
}else{
fileProcess(list[i]);
}
}
}
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 class Test4{
public static void main(String[] args) {
FileSearch seatcher = new FileSearch("/home/fuhd/apk/gnapk/tencent/122","com.ymall.presentshop.apk");
Thread thread = new Thread(seatcher);
thread.start();
//等待十秒,然后中断线程
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
}
}
在本范例中,我们使用了Java异常来控制线程的中断。当运行这个范例时,程序将进入文件夹查找是否包含指定的文件。例如,如果要查找的文件夹目录结构是\b\c\d,这个程序将递归调用processDirectory()方法3次。不管递归调用了多少次,只要线程检测到它已经被中断了,就会立即抛出InterruptedException异常,然后继续执行run()方法。
标签:
原文地址:http://my.oschina.net/fhd/blog/403636