天天看点

java多线程--停止一个线程的方法小结(来自java多线程编程核心技术)

1.中断方法停止线程:

package thread_stop.way;

public class MyThread extends Thread {

	public void run() {

		try{
			
			for (int i = 0; i < 500000; i++) {
				if (this.interrupted()) {
					System.out.println("已经是停止状态了,我要求退出");
					throw new InterruptedException();
				}

				System.out.println("i= " + (i + 1));
			}

			System.out.println("停止之后的测试");
			
		}catch(InterruptedException e){
			
			System.out.println("进入Mythread线程状态异常");
			//e.printStackTrace();
		}
		

	}

}
           

2.在抛异常的方法来结束线程:

package thread_stop.way;

public class SleepThread extends Thread{
	
	public void run(){
		
		try{
			
			System.out.println("run begin...");
			Thread.sleep(20000);
			System.out.println("run end...");
		}catch(InterruptedException e){
			System.out.println("在sleep中停止一个线程,实际也是抛异常的方法");
		
			e.printStackTrace();
		
		}
	}

}
           

3.对于线程中循环读取一些信息,如,读取网络文件,刚设一个标志加中断的方式,在捕获的异常中停止一个线程,推荐使用标识+异常捕获的方式停止 一个线程:

package thread_stop.way;

public class UseReturnThread extends Thread{
	
	public void run(){
		
		while(true){		//此处可以添加一个boolean 型的标识,如while(flag),然后在catch的异常中将flag=flse即可
			
			if(this.interrupted()){
				System.out.println("停止了...");
				
				return;
			}
			
			System.out.println("timer = "+System.currentTimeMillis());
		}
	}

}
           

4.测试:

package thread_stop.way;

/**
 * 本实例测试线程停止的方法
 * 
 * @author Administrator
 *
 */
public class Main {

	public static void main(String[] args) {

		
		//excetionStop();
		
		//sleepStop();
		
		userReturnStopThread();
	}

	/**
	 * 在线程抛异常来终止一个线程
	 */
	public static void excetionStop() {

		try {

			MyThread thread = new MyThread();

			thread.start();

			Thread.sleep(2000); // 主线程休眠2秒

			thread.interrupt(); // 将测试线程置为中断状态

		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("主线程终止");
	}

	
	/**
	 * 在休眠中停止线程
	 */
	public static void sleepStop(){
		
		try{
			
			SleepThread thread = new SleepThread();
			thread.start();
			Thread.sleep(200);		//主线程休眠 ,这里使主线程休眠 ,主要是想测试线程完全启动起来
			
			thread.interrupt();
			
			
		}catch(InterruptedException e){
			
			System.out.println("主线程异常。。。");
			e.printStackTrace();
		}
		
		System.out.println("主线程停止。。。");
		
	}


	
	/**
	 * 使用return +interrupt来停止一个线程
	 * @throws InterruptedException 
	 */
	public static void userReturnStopThread() {
		
		try{
			
			UseReturnThread thread = new UseReturnThread();
			thread.start();
			
			Thread.sleep(2000);
			
			thread.interrupt();
		}catch(InterruptedException e){
			
			System.out.println("main thread excetion...");
			e.printStackTrace();
		}
		
		System.out.println("main thread stop");
		
		
	}

	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
           

继续阅读