您的位置:首页 > 其它

线程中断问题详解

2012-07-31 21:57 120 查看
//线程的中断操作(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)线程没有被中断,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方法后的内容依然会被执行,相当于线程被唤醒进入了正常执行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: