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









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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值