Javaマルチスレッド(2)--スレッドの割り込みと割り込みの制御


Javaプログラムに実行スレッドが1つしかない場合は、すべてのスレッドが終了したときにのみこのプログラムが実行されます.より正確には、すべての非デーモンスレッドの実行が終了するか、いずれかのスレッドが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 
", 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();// , , // 。 } }