Java多线程(2)--线程的中断和中断的控制


如果Java程序不只有一个执行线程,只有当所有线程结束的时候这个程序才能运行结束。更确切的说是所有的非守护线程运行结束的时候,或者其中一个线程调用了System.exet()方法时,程序才运行结束。

Java提供了中断机制,我们可以采用它来结束一个线程。我们创建一个线程,使其运行5秒后通过中断机制强制使其终止。程序检查数字是否是质数。

package com.concurrency;

public class PrimeGenerator extends Thread{ //继承自Thread类,覆写run方法即可。
	@Override
	public void run(){
		long number = 1L;//检查一个数字是否是质数
		while(true){
			if(isPrime(number)){
				System.out.println(number);//是质数就打印
			}
			if(isInterrupted()){//每检查一个数就检查该线程是否被中断
				System.out.println("Has been Interrupted!");
				return;
			}
			number++;
		}
	}
	private boolean isPrime(long number) {//判断质数的函数
		if(number < 2)
			return true;
		for(long i = 2; i < number; i++){
			if((number % i) == 0){
				return false;
			}
		}
		return true;
	}
	public static void main(String[] args) {
		Thread task = new PrimeGenerator();//创建对象
		task.start();//调用start就会运行run函数.就会引出来一个线程到一边去执行。
				//值函数还是会继续向下执行,两者互不干扰
		try{
			Thread.sleep(2000);//让线程休眠2秒
		} catch(InterruptedException e) {
			e.printStackTrace();
		}
		task.interrupt();
	}

}

上面是如何去中断执行中的线程,可以在线程对象中控制这个中断。有更好的机制来控制线程的中断,Java提供了InterruptedException异常来支持。当检查到线程中断的时候就抛出这个异常,然后在run中捕获并处理这个异常。

下述方法的目的是在指定路径中查找文件是否存在。可以迭代查找文件夹。

package com.concurrency;

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

public class FileSearch implements Runnable{

	private String initPath;//初始要检索的文件路径
	private String fileName;//要检索的文件名
	public FileSearch(String intiString, String fileName){
		this.initPath = intiString;
		this.fileName = fileName;
	}
	
	@Override
	public void run(){//实现了接口也就要是实现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()){//如果线程中断了,就在这里抛出异常,在run中捕获异常
			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();
		}
	}
	public static void main(String[] args) {
		FileSearch searcherFileSearch = new FileSearch("C:\\", "autoexec.bat");
		Thread thread = new Thread(searcherFileSearch);
		thread.start();
		try{
			TimeUnit.SECONDS.sleep(10);
		} catch(InterruptedException e){
			e.printStackTrace();
		}
		thread.interrupt();//在这里中断线程,因为线程在几个复杂的方法中,且有了递归方法
		//的调用。通过借助异常的方式来捕获异常
	}

}












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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值