上篇讲到使用异常处理的方法来停止线程,本篇将继续探讨停止线程的方式和与停止线程有关的一些知识点。
3、在沉睡中停止线程
如果线程在sleep()的状态下被终止,会是什么情况呢?可以理解成一个人在睡觉的时候被杀害了,那么这个人睡觉之后的行为便不会再进行,比如说他不会再醒过来。
这里继续创建Mythread类
public class Mythread extends Thread{ @Override public void run() { super.run(); try { System.out.println("我开始睡觉啦!"); Thread.sleep(200000); System.out.println("我醒来啦!"); } catch(InterruptedException e) { System.out.println("在沉睡中被杀掉了!没法醒过来了!"+this.isInterrupted()); e.printStackTrace(); } } }
Run中包含一个main方法
public class Run { public static void main(String args[]) { try { Mythread mt = new Mythread(); mt.start(); Thread.sleep(1000); mt.interrupt(); } catch (InterruptedException e) { e.printStackTrace(); } } }
运行结果
我开始睡觉啦!
在沉睡中被杀掉了!没法醒过来了!false
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at Practice.Mythread.run(Mythread.java:9)
从打印结果来看,如果在sleep的状态下终止某一个线程,会进入catch语句,并且将他的终止状态清除,设为false。
另一种情况,如果是在 sleep()之前就遇到了interrupt()的话一样会直接进入catch语句,并结束线程。
4、使用return停止线程
将方法interrupt()与return结合起来也能终止线程。修改Mythread类与main方法如下
public class Mythread extends Thread{ @Override public void run() { while(true) { if(this.isInterrupted()){ System.out.println("停止!"); return; } System.out.println("计时:"+System.currentTimeMillis()); } } }
public class Run { public static void main(String args[]) throws InterruptedException { Mythread mt = new Mythread(); mt.start(); Thread.sleep(2000); mt.interrupt(); } }
在检查到线程状态为终止的时候,不再输出时间,返回结果
运行如下:
计时:1525424532412
计时:1525424532412
计时:1525424532412
计时:1525424532412
计时:1525424532412
计时:1525424532412
停止!
虽然可以使用interrput()与return结合的方式来终止线程,但是还是推荐使用抛异常的方式终止线程,因为跑出的异常可以继续向上层传递,使得线程终止这一事件得以传播。