`

线程interrupt方法中断的实质

    博客分类:
  • java
阅读更多

首先有两段代码:

代码1:

view plaincopy to clipboardprint?
//线程的中断操作(1)
class MyThread implements Runnable
{
 public void run(){
  System.out.println("1、进入run方法");
  try{
   Thread.sleep(10000);       //sleep方法会抛出一个中断异常
  }catch(InterruptedException e){
   System.out.println("2、线程被中断");  //当sleep被打断时,则执行此中断处理
  }
  System.out.println("3、run方法执行完成");
 }
}
public class ThreadInterruptDemo01
{
 public static void main(String args[]){
  MyThread my = new MyThread();
  Thread t = new Thread(my);
  t.start();
  try{
   Thread.sleep(2000);   //主线程休息2秒
  }
  catch(Exception e){}
  t.interrupt();    //中断线程
 }
 
 
}

代码2:

view plaincopy to clipboardprint?
//线程的中断操作(2)线程没有被中断,interrupt只能中断sleep,wait等方法
class MyThread implements Runnable
{
 public void run(){
  System.out.println("1、进入run方法");
  for(int i = 0;i<=10000;i++){
   System.out.println("线程在执行"+"--"+i);
  }
  System.out.println("线程正常执行完毕");
 }
}
public class ThreadInterruptDemo02
{
 public static void main(String args[]){
  MyThread my = new MyThread();
  Thread t = new Thread(my);
  t.start();
  
  t.interrupt();    //中断线程
 }
}

     通过两段代码的运行结果可以知道,代码1的中断实现了,而代码2的中断没有实现,interrupt并没有中断线程的执行,而是中断了sleep的执行。原因何在,这与Interrupt的中断内容有关。interrupt只能中断sleep,wait等方法,而通过查询api可以看到,sleep和wait都有InterruptedException(中断异常)需要处理。所以可以这样看:interrupt只能中断会抛出中断异常的方法,这才是interrupt的实际作用。

      还有一点需要注意,当sleep方法被中断后,sleep方法后的内容依然会被执行,相当于线程被唤醒进入了正常执行。

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/xiaoya629/archive/2010/04/21/5508011.aspx

分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

Global site tag (gtag.js) - Google Analytics