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

来源:互联网 发布:网络医托 编辑:程序博客网 时间:2024/04/30 10:57


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

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

package com.concurrency;public class PrimeGenerator extends Thread{ //继承自Thread类,覆写run方法即可。@Overridepublic 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;}@Overridepublic 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
原创粉丝点击