一基本概念:
1.Interrupted 是判断调用这行代码的线程是否中断,,重复调用这个方法会清除中断状态,换句话说连续调用2次该方法即使第一次返回true【中断】第二次也会返回false。
2.this.isInterrupted它是测试线程是否已经中断,测试Thread对象是否中断状态,但不清除状态标识。
二代码示例:
示例一:
自定义线程类:
public class MyThread extends Thread{
@Override
public void run(){
super.run();
for (int i=0;i<500000;i++){
System.out.println("i="+(i+1));
}
}
}
运行类Run.java
public class run{
public static void main(String[ ] args){
try{
MyThread thread=new MyThread();
thread.start();
Thread.sleep(1000);
thread.interrupt();
System.out.println("是否中断1?="+thread.interrupted());
System.out.println("是否中断1?="+thread.interrupted());
}catch(InterruptedException e){
System.out prinln("main catch");
e.printStackTrace();
}
System.out prinln("end!");
}
}
运行结果为:
证明:interrupted()是判断main线程是否中断,它是main线程调用的方法;
示例二:
Run2.java
public class run2{
public static void main(String[ ] args){
Thread.currentThread.interrupt(); //中断线程
System.out.println("是否中断1?="+Thread.interrupted());
System.out.println("是否中断1?="+Thread.interrupted());
System.out prinln("end!");
}
}
运行结果:
证明:interrupted()连续连词调用 第二次为flase 每次调用清除中断状态。
示例三: Run3.java
public class run3{
public static void main(String[ ] args){
try{
MyThread thread=new MyThread();
thread.start();
Thread.sleep(1000);
thread.interrupt();
System.out.println("是否中断1?="+thread.isInterrupted());
System.out.println("是否中断1?="+thread.isInterrupted());
}catch(InterruptedException e){
System.out prinln("main catch");
e.printStackTrace();
}
System.out prinln("end!");
}
}
运行结果为:
证明:isInterrupted测试Thread对象是否已经中断状态,但不清除中断标志。