package test; public class Test5 extends Thread { @Override public void run() { for (int i = 0; i < 500000; i++) { System.out.println("i=" + (i + 1)); } } public static void main(String[] args){ try { Test5 thread = new Test5(); thread.start(); Thread.sleep(4000); thread.interrupt(); // Thread.sleep(400); System.out.println("是否停止1?=" + thread.isInterrupted()); System.out.println("是否停止2?=" + thread.isInterrupted()); } catch (InterrupedException e) { System.out.println("main catch"); e.printStackTrace(); } System.out.println("end!"); } }
运行结果:
i=499994
i=499995
i=499996
i=499997
i=499998
i=499999
i=500000
是否停止1?=false
是否停止2?=false
end!
本来该返回true,却返回了false,查了一下有人说是在主线程休眠的时候thread线程已经执行完毕,所以后面的interrupted()设置的终端标记没有用了。照这个思路我改了一下代码,将Thread.sleep(4000)改为Thread.sleep(40)。
package test; public class Test5 extends Thread { @Override public void run() { for (int i = 0; i < 500000; i++) { System.out.println("i=" + (i + 1)); } } public static void main(String[] args){ try { Test5 thread = new Test5(); thread.start(); Thread.sleep(40); thread.interrupt(); // Thread.sleep(400); System.out.println("是否停止1?=" + thread.isInterrupted()); System.out.println("是否停止2?=" + thread.isInterrupted()); } catch (InterrupedException e) { System.out.println("main catch"); e.printStackTrace(); } System.out.println("end!"); } }
而结果却是:
i=499994
i=499995
i=499996
i=499997
i=499998
i=499999
i=500000
这时thread.interrupted后面的代码却不会执行了。
第一种isInterrupted()返回false,我查了一下资料上说,如果线程正在执行wait,sleep,join方法,你调用interrupt()方法,会抛出InterruptedException异常。而一个抛出了异常的线程的状态马上就会被置为非中断状态。InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.
第二种情况在一个线程正在执行还没有执行完的时候被标记为中断状态会导致整个程序停止,测试代码如下
public class Test5 extends Thread { @Override public void run() { for (int i = 0; i < 50; i++) { System.out.println("i=" + (i + 1)); } } public static void main(String[] args){ try { Test5 thread = new Test5(); thread.start(); thread.interrupt(); System.out.println("是否停止1?=" + thread.isInterrupted()); System.out.println("是否停止2?=" + thread.isInterrupted()); thread.sleep(4000); } catch (Exception e) { System.out.println("main catch"); e.printStackTrace(); } System.out.println("end!"); } }
我们会发现thread.sleep(4000)之前的代码都会执行,而System.out.println("end!")不会执行