Java 多线程 - 线程 - 中断 - 3

本文介绍了一种利用Java中的InterruptedException来实现线程中断控制的方法。通过一个具体的例子——搜索文件夹及其子文件夹中的特定文件,展示了如何在run()方法中捕获并处理InterruptedException来控制线程是否中断。

实例背景

如果线程实现了复杂的算法并且分布在几个方法中,或者线程里面有递归调用的方法,这样的话,就得需要使用一个更好的机制来控制线程的中断。为了达到这个目的,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 被中断...

 

转载于:https://my.oschina.net/u/1387400/blog/1525113

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值