本文共 1583 字,大约阅读时间需要 5 分钟。
interrupted():测试当前线程是否已经中断(当前正在执行的线程,是静态方法)。
isInterrupted():测试线程是否已经中断。(对象线程)。
interrupted()方法具有清除状态的功能,isInterrupted()并未清除状态标志。
示例:
public class Run { public static void main(String[] args){ MyThread thread=new MyThread(); thread.start(); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } thread.interrupt(); System.out.println("是否停止1?="+MyThread.interrupted()); System.out.println("是否停止2?="+MyThread.interrupted()); System.out.println("end!"); }}i=1 i=2 i=3 i=4 i=5 是否停止1?=false 是否停止2?=false end!
因为打断的是thread线程,而正在执行的是main线程,所以返回false
改成打断主线程就可以了:
public class Run { public static void main(String[] args){ MyThread thread=new MyThread(); thread.start(); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } Thread.currentThread().interrupt(); System.out.println("是否停止1?="+MyThread.interrupted()); System.out.println("是否停止2?="+MyThread.interrupted()); System.out.println("end!"); }}
i=1
i=2 i=3 i=4 i=5 是否停止1?=true 是否停止2?=false end!public class Run { public static void main(String[] args){ MyThread thread=new MyThread(); thread.start(); thread.interrupt(); System.out.println("是否停止1 ? ="+thread.isInterrupted()); System.out.println("是否停止2 ? ="+thread.isInterrupted()); System.out.println("end!"); }}是否停止1 ? =true i=1 是否停止2 ? =true end! i=2 i=3 i=4 i=5
转载地址:http://pojqi.baihongyu.com/