线程中断之interrupt和stop方法

 从阿里的笔试和网易游戏的电面中暴露了关于线程并发方面基础知识掌握的不到位, 现在从头再来学习一遍。

 首先我们想中断一个线程,可以使用interrupt和stop两种方式。 

首先说interrupt, 它没有stop那么的粗暴,因为可以用catch捕捉到InterruptedException这个异常

package thread;


import java.util.Date;


public class interrupt {
	
	public static void main(String[] args){
		MyThread mythread =new MyThread();
		mythread.start();
		try{
			Thread.sleep(10000);
		}catch(InterruptedException e){
			
		}
		mythread.interrupt();
		//mythread.flag=false;
		
		
	}
}
	
class MyThread extends Thread{
	public boolean flag =true;
	public void run(){
		while(true){
			
		
	
			System.out.println(new Date());
			try{
				sleep(1000);
			}catch(InterruptedException e){
				System.out.println("Oh,no!!");
				return;
			}
		
		}
	}
}



这里主函数中10000ms后打断了这个线程

输出如下:

Thu Apr 03 20:36:11 CST 2014
Thu Apr 03 20:36:12 CST 2014
Thu Apr 03 20:36:13 CST 2014
Thu Apr 03 20:36:14 CST 2014
Thu Apr 03 20:36:15 CST 2014
Thu Apr 03 20:36:16 CST 2014
Thu Apr 03 20:36:17 CST 2014
Thu Apr 03 20:36:18 CST 2014
Thu Apr 03 20:36:19 CST 2014
Thu Apr 03 20:36:20 CST 2014
Oh,no!!


如果使用stop方法,则更加粗暴一些:

Thu Apr 03 20:49:06 CST 2014
Thu Apr 03 20:49:07 CST 2014
Thu Apr 03 20:49:08 CST 2014
Thu Apr 03 20:49:09 CST 2014
Thu Apr 03 20:49:10 CST 2014
Thu Apr 03 20:49:11 CST 2014
Thu Apr 03 20:49:12 CST 2014
Thu Apr 03 20:49:13 CST 2014
Thu Apr 03 20:49:14 CST 2014
Thu Apr 03 20:49:15 CST 2014

因为此时线程直接终止,没有catch异常的机会, 无法对线程结束这一行为作出任何补救动作。


无论是interrupt还是stop都是不安全的做法,因为如果我们在线程进行时打开了某些资源,那么这样粗暴的结束资源将无法正确关闭,所以提倡以下做法:

package thread;

import java.util.Date;

public class interrupt {
	
	public static void main(String[] args){
		MyThread mythread =new MyThread();
		mythread.start();
		try{
			Thread.sleep(10000);
		}catch(InterruptedException e){
			
		}
		//mythread.stop();
		mythread.flag=false;
		
		
	}
}
	
class MyThread extends Thread{
	public boolean flag =true;
	public void run(){
		while(flag){
			
		
	
			System.out.println(new Date());
			try{
				sleep(1000);
			}catch(InterruptedException e){
				System.out.println("Oh,no!!");
				return;
			}
		
		}
	}
}

用一个标志flag来控制线程的结束

你可能感兴趣的:(java)