线程中断之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来控制线程的结束

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值