4.多线程学习--操作线程的中断机制

package com.jackson.deng.concurrent.chapter1.four;

import java.io.File;
import java.util.concurrent.TimeUnit;

/**
 * 简意为:在指定路径下找到指定文件,如果10秒没有找到,就打断这个文件搜索的线程.<br>
 * 应用场景:<br>
 *  接收邮件的时候,如果超过指定时间没有接收到,给出不响应的消息 
 * 
 * @author jackson
 *
 */
public class FileSearchThreadInterrupt {

	public class FileSearch extends Thread {

		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) {
					e.printStackTrace();
				}
			}
		}

		private void directoryProcess(File file) throws InterruptedException {
			File[] listFiles = file.listFiles();
			if (listFiles != null) {
				for (File f : listFiles) {
					if (f.isDirectory()) {
						directoryProcess(f);
					} else {
						fileProcess(f);
					}
				}
			}
		}

		private void fileProcess(File file) throws InterruptedException {
			if (file.getName().equals(fileName)) {
				System.out.println(Thread.currentThread().getName() + " : " + file.getAbsolutePath());
				Thread.currentThread().stop();
			}

			if (isInterrupted()) {
				throw new InterruptedException();
			}
		}
	}

	public static void main(String[] args) {
		FileSearchThreadInterrupt fsti = new FileSearchThreadInterrupt();
		Thread task = fsti.new FileSearch("c:\\", "autoexec.bat");
		task.start();
		try {
			TimeUnit.SECONDS.sleep(10);
			task.interrupt();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

代码挺简单的,就不多做解释了..给出找到和没找到的运行结果


下面是找到了的


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值