您的位置:首页 > 编程语言 > Java开发

Java并发学习之四——操作线程的中断机制

2014-08-12 17:17 513 查看
本文是学习网络上的文章时的总结,感谢大家无私的分享。

1、如果线程实现的是由复杂算法分成的一些方法,或者他的方法有递归调用,那么我们可以用更好的机制来控制线程中断。为了这个Java提供了InterruptedException异常。当你检测到程序的中断并在run()方法内捕获,你可以抛这个异常。
2、InterruptedException异常是由一些与并发API相关的Java方法,如sleep()抛出的。
下面以程序解释
package chapter;

import java.io.File;

/**
* <p>
* Description:我们将实现的线程会根据给定的名称在文件件和子文件夹里查找文件,这个将展示如何使用InterruptedException异常来控制线程的中断。
* </p>
*
* @author zhangjunshuai
* @version 1.0 Create Date: 2014-8-11 下午3:10:29 Project Name: Java7Thread
*
*          <pre>
* Modification History:
*             Date                                Author                   Version          Description
* -----------------------------------------------------------------------------------------------------------
* LastChange: $Date::             $      $Author: $          $Rev: $
* </pre>
*
*/
public class FileSearch implements Runnable {
private String initPath;
private String fileName;

public FileSearch(String initPath, String fileName) {
this.fileName = fileName;
this.initPath = initPath;
}

@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();
}
}

}
package chapter;

import java.util.concurrent.TimeUnit;

public class Main4 {

/**
* <p>
* </p>
* @author zhangjunshuai
* @date 2014-8-12 下午3:40:54
* @param args
*/
public static void main(String[] args) {
FileSearch searcher = new FileSearch("c:\\", "unintall.log");
Thread thread = new Thread(searcher);
thread.start();

try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}

thread.interrupt();

}

}


请注意程序中使用的是Thread.interrupted(),此方法和
isInterrupted()是有区别的。


另:JDK的TimeUnit是学习枚举的好例子

参考:

并发编程网
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: