Java并发编程实例--4.控制线程打断
Java提供了InterruptedException异常,当我们检测到线程被打断时可以抛出并在run()方法中进行捕捉。
本例中,我们将开发一个程序以实现根据文件名称在指定文件夹(包括其子目录)中搜索它。
本例中,我们将开发一个程序以实现根据文件名称在指定文件夹(包括其子目录)中搜索它。
以此来介绍如何使用InterruptedException异常。
FileSearch.java
package com.dylan.thread.ch1.c04;
import java.io.File;
/**
* @author xusucheng
* @create 2018-04-13
**/
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);
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();
}
}
}
Main.java
package com.dylan.thread.ch1.c04;
import java.util.concurrent.TimeUnit;
/**
* @author xusucheng
* @create 2018-04-23
**/
public class Main {
public static void main(String[] args) {
FileSearch searcher=new FileSearch("C:\\","test.log");
Thread thread=new Thread(searcher);
thread.start();
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
}
}
由于C盘下文件无数,要搜索的文件通常在10s内无法完成,所以线程被打断了。
输出:
Thread-0: The search has been interrupted