Java併發學習之四——操作線程的中斷機制

本文是學習網絡上的文章時的總結,感謝大家無私的分享。

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是學習枚舉的好例子

參考:

併發編程網

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章