标签:start read 读取 public 12px 标记 stopped and 抛出异常
public class Run {public static void main(String[] args) {try {MyThread thread = new MyThread();thread.start();Thread.sleep(2000);thread.interrupt();//请求中断MyThread线程} catch (InterruptedException e) {System.out.println("main catch");e.printStackTrace();}System.out.println("end!");}}
public class MyThread extends Thread {@Overridepublic void run() {super.run();for (int i = 0; i < 500000; i++) {if (this.interrupted()) {System.out.println("should be stopped and exit");break;}System.out.println("i=" + (i + 1));}System.out.println("this line is also executed. thread does not stopped");//尽管线程被中断,但并没有结束运行。这行代码还是会被执行}}
当MyThread获得CPU执行时,第6行的 if 测试中,检测到中断标识被设置。即MyThread线程检测到了main线程想要中断它的 请求。
大多数情况下,MyThread检测到了中断请求,对该中断的响应是:退出执行(或者说是结束执行)。
但是,上面第5至8行for循环,是执行break语句跳出for循环。但是,线程并没有结束,它只是跳出了for循环而已,它还会继续执行第12行的代码....
因此,我们的问题是,当收到了中断请求后,如何结束该线程呢?
一种可行的方法是使用 return 语句 而不是 break语句。。。。。哈哈。。。
不过使用return 没有抛异常那么好,不能将事件传播
优雅的解决
public class MyThread extends Thread {@Overridepublic void run() {super.run();try{for (int i = 0; i < 500000; i++) {if (this.interrupted()) {System.out.println("should be stopped and exit");throw new InterruptedException();}System.out.println("i=" + (i + 1));}System.out.println("this line cannot be executed. cause thread throws exception");//这行语句不会被执行!!!}catch(InterruptedException e){System.out.println("catch interrupted exception");e.printStackTrace();}}}
当MyThread线程检测到中断标识为true后,在第9行抛出InterruptedException异常。这样,该线程就不能再执行其他的正常语句了(如,第13行语句不会执行)。
因此,上面就是一个采用抛出异常的方式来结束线程的示例。尽管该示例的实用性不大。原因是我们 生吞了中断。
在第14行,我们直接catch了异常,然后打印输出了一下而已,调用栈中的更高层的代码是无法获得关于该异常的信息的。
第16行的e.printStackTrace()作用就相当于
1.仅仅记录 InterruptedException 也不是明智的做法,因为等到人来读取日志的时候,再来对它作出处理就为时已晚了。
@Override public void run() throws InterruptedException{//这是错误的 //do something...
代码改良
public class MyThread extends Thread {@Overridepublic void run() {super.run();try{for (int i = 0; i < 500000; i++) {if (this.interrupted()) {System.out.println("should be stopped and exit");throw new InterruptedException();}System.out.println("i=" + (i + 1));}System.out.println("this line cannot be executed. cause thread throws exception");}catch(InterruptedException e){/**这样处理不好* System.out.println("catch interrupted exception");* e.printStackTrace();*/Thread.currentThread().interrupt();//这样处理比较好}}}
标签:start read 读取 public 12px 标记 stopped and 抛出异常
原文地址:http://www.cnblogs.com/signheart/p/8bb7a43d9def66f6369ecfcfc56bffde.html