码迷,mamicode.com
首页 > 编程语言 > 详细

Java并发学习之四——操作线程的中断机制

时间:2014-08-12 19:08:24      阅读:281      评论:0      收藏:0      [点我收藏+]

标签:中断机制

本文是学习网络上的文章时的总结,感谢大家无私的分享。

1、如果线程实现的是由复杂算法分成的一些方法,或者他的方法有递归调用,那么我们可以用更好的机制来控制线程中断。为了这个Java提供了InterruptedException异常。当你检测到程序的中断并在run()方法内捕获,你可以抛这个异常。

2InterruptedException异常是由一些与并发API相关的Java方法,如sleep()抛出的。

下面以程序解释

package chapter;

import java.io.File;

/**
 * <p>
 * Description:我们将实现的线程会根据给定的名称在文件件和子文件夹里查找文件,这个将展示如何使用InterruptedException异常来控制线程的中断。
 * </p>
 * 
 * @author zhangjunshuai
 * @version 1.0 Create Date: 2014-8-11 下午3:10:29 Project Name: Java7Thread
 * 
 *          <pre>
 * Modification History: 
 *             Date                                Author                   Version          Description 
 * -----------------------------------------------------------------------------------------------------------  
 * LastChange: $Date::             $      $Author: $          $Rev: $
 * </pre>
 * 
 */
public class FileSearch implements Runnable {
	private String initPath;
	private String fileName;

	public FileSearch(String initPath, String fileName) {
		this.fileName = fileName;
		this.initPath = initPath;
	}

	@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();
		}
	}

}
package chapter;

import java.util.concurrent.TimeUnit;

public class Main4 {

	/**
	 * <p>
	 * </p>
	 * @author zhangjunshuai
	 * @date 2014-8-12 下午3:40:54
	 * @param args
	 */
	public static void main(String[] args) {
		FileSearch searcher = new FileSearch("c:\\", "unintall.log");
		Thread thread = new Thread(searcher);
		thread.start();
		
		try {
			TimeUnit.SECONDS.sleep(10);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		thread.interrupt();

	}

}

请注意程序中使用的是Thread.interrupted(),此方法和isInterrupted()是有区别的。

另:JDK的TimeUnit是学习枚举的好例子

参考:

并发编程网

Java并发学习之四——操作线程的中断机制,布布扣,bubuko.com

Java并发学习之四——操作线程的中断机制

标签:中断机制

原文地址:http://blog.csdn.net/junshuaizhang/article/details/38518217

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!