只要是在运行wait(),sleep(),join()的方法,它就会声明一个InterruptedException异常,也就是意味着这些方法并不是一定能执行完成,因为当调用线程的interrupt()方法时,就会中断这个阻塞的办法,从而进入到异常中,代码如下
package com.xiaojiezhu.thread; /** * @author xiaojie.zhu */ public class ThreadBreak2 implements Runnable { @Override public void run() { try { Thread.sleep(20000); System.out.println("这段话不会输出"); } catch (InterruptedException e) { //如果在sleep()的过程中调用了interrupt()方法,就会进入这里,因为会强行中断sleep() //这里打印出来的中断标记为false,因为只要进入了InterruptedException异常,中断标记就会被清除掉 System.out.println("中断标记为:" + Thread.currentThread().isInterrupted()); System.out.println("输出异常"); e.printStackTrace(); } } public static void main(String[] args) throws InterruptedException { Thread t = new Thread(new ThreadBreak2()); t.start(); Thread.sleep(100); t.interrupt(); System.out.println("over"); } }
打印结果如下
over
中断标记为:false
输出异常
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.xiaojiezhu.thread.ThreadBreak2.run(ThreadBreak2.java:10)
at java.lang.Thread.run(Thread.java:748)
注意:因为只要进入了InterruptedException异常,中断标记就会被清除掉
这里会衍生出另一种情况,就是如果在进入阻塞方法之前,就有了中断标记呢?会发生什么,就如下的代码:
for(int i = 0 ; i < 10000 ; i ++){ System.out.println(i); } try { System.out.println("开始sleep"); Thread.sleep(20000); System.out.println("结束sleep"); } catch (InterruptedException e) { e.printStackTrace(); }
实际上它会先执行完上面的for循环,因为for循环中是无法中止的,在进入sleep()的时候,瞬间就抛出异常
完整的测试代码如下
package com.xiaojiezhu.thread; /** * @author xiaojie.zhu */ public class ThreadBreak3 implements Runnable { @Override public void run() { for(int i = 0 ; i < 10000 ; i ++){ System.out.println(i); } try { System.out.println("开始sleep"); Thread.sleep(20000); System.out.println("结束sleep"); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { Thread thread = new Thread(new ThreadBreak3()); thread.start(); thread.interrupt(); } }
打印结果如下
9997 9998 9999 开始sleep java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) at com.xiaojiezhu.thread.ThreadBreak3.run(ThreadBreak3.java:15) at java.lang.Thread.run(Thread.java:748)
thread.stop()方法是一个不安全的方法,已经不推荐使用了,但是在目前的代码中,还能正常使用,我们不推荐这样使用,但是这里介绍一下
package com.xiaojiezhu.thread; /** * @author xiaojie.zhu */ public class ThreadBreak4 implements Runnable { @Override public void run() { System.out.println("进入线程"); try { Thread.sleep(20000); System.out.println("结束线程"); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { Thread t = new Thread(new ThreadBreak4()); t.start(); try { Thread.sleep(200); t.stop(); System.out.println("over"); } catch (InterruptedException e) { e.printStackTrace(); } } }
打印结果如下
进入线程
over