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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构