线程中断问题详解
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方法后的内容依然会被执行,相当于线程被唤醒进入了正常执行。
相关文章推荐
- 多线程的使用——中断线程详解(Interrupt)
- 并发编程学习总结(三) : 线程的中断详解
- 深入分析Java线程中断问题
- Java多线程之中断线程(Interrupt)的使用详解
- 详解Java多线程编程中线程的启动、中断或终止操作
- 详解Java多线程编程中线程的启动、中断或终止操作
- Java多线程之中断线程(Interrupt)的使用详解
- 中断线程详解
- boost库中thread多线程详解5——谈谈线程中断
- 【Boost】boost库中thread多线程详解5——谈谈线程中断
- 【转】java线程阻塞中断和LockSupport的常见问题
- java线程中断 interrupt详解
- 中断线程详解(Interrupt)
- Java线程阻塞中断和LockSupport问题
- 详解Java线程中断知识点
- 关于线程中断的问题
- java 线程退出问题(interrupt()与中断标志)
- 关于中断线程问题
- java线程之中断interrupt详解
- Java线程阻塞中断和LockSupport问题