interrupt()理解
2014-04-12 14:27
134 查看
之前对interrupt()方法一直不太理解,可能是这个名字太具有迷惑性了吧。
interrupt不能中断正在运行的线程,如下代码
interrupt不能中断正在运行的线程,如下代码
class Example1 extends Thread { boolean stop = false; public static void main(String args[]) throws Exception { Example1 thread = new Example1(); System.out.println("Starting thread..."); thread.start(); Thread.sleep(3000); System.out.println("Interrupting thread..."); thread.interrupt(); System.out.println("thread interrupt()" + thread.isInterrupted()); Thread.sleep(3000); System.out.println("Stopping application..."); // System.exit(0); } public void run() { while (!stop) { System.out.println("Thread is running..."); long time = System.currentTimeMillis(); while ((System.currentTimeMillis() - time < 1000)) { } } System.out.println("Thread exiting under request..."); } }但是上面的代码还是有漏洞的,Example1对thread执行了interrupt操作,没有中断thread是因为interrupt方法只是在目标线程中设置了一个标志,表示它已经被中断。Example1对thread设置了中断标志但并没有检查这个标志是否被设置,所以Example1无法中断thread。对上面代码修改如下
class Example1 extends Thread { boolean stop = false; public static void main(String args[]) throws Exception { Example1 thread = new Example1(); System.out.println("Starting thread..."); thread.start(); Thread.sleep(3000); System.out.println("Interrupting thread..."); thread.interrupt(); System.out.println("thread interrupt()" + thread.isInterrupted()); Thread.sleep(3000); System.out.println("Stopping application..."); // System.exit(0); } public void run() { //检查中断标志 while (!stop && !Thread.currentThread().isInterrupted()) { System.out.println("Thread is running..."); long time = System.currentTimeMillis(); while ((System.currentTimeMillis() - time < 1000)) { } } System.out.println("Thread exiting under request..."); } }
相关文章推荐
- Thread类的interrupt,interrupted,isInterrupted方法的理解
- TI C66x DSP 系统events及其应用 - 5.3.1(Interrupt之eventCombiner理解)
- 对Java中interrupt、interrupted和isInterrupted的理解
- 理解interrupt
- 理解interrupt()方法
- 关于interrupt,interrupted和isInterrupted的理解
- Thread类的interrupt,interrupted,isInterrupted方法的理解
- java interrupt理解
- interrupt、isinterrupt、interrupted的理解和使用
- 理解Java的Thread中的Interrupt机制
- Thread类的interrupt,interrupted,isInterrupted方法的理解
- java线程经典理解之Interrupt
- 理解java线程的中断(interrupt)
- 中断线程 —— interrupt() 以及对其理解
- 理解java线程的中断(interrupt)
- Java多线程 -- JUC包源码分析7 -- 对Interrupt的深刻理解
- Thread类的interrupt,interrupted,isInterrupted方法的理解
- 【转】理解java线程的中断(interrupt)
- Thread.interrupt()方法理解
- 对于interrupt,interrupted 和 isInterrupted的一些理解