interrupt和isInterrupted,Thread.interrupted()区别 中断协商机制
interrupt仅仅是设置线程的中断状态为true,发起一个协商,并不会立即中断线程:中断只是一种协商机制,修改中断标识位,仅此而已;不是立刻打断;
thread.interrupt():发出一个中断申请;
isInterrupted返回当前线程的中断状态;true:有中断申请 fale:无中断申请;
Thread.interrupted();//静态方法 做2件事:测试当前线程是否被中断(检查中断标志),返回一个boolean并清除中断状态;
代码1
Thread t1 = new Thread(()->{
while(true) {
if(Thread.currentThread().isInterrupted()) {
break;
}
try {
//处于阻塞状态, 在别的线程中调用interrupt时,退出阻塞状态
// 抛出interruptException异常!
Thread.sleep(2*1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();//
为什么要在异常处,再调用一次??
因为抛出异常后中断标志清零,为false进入 无限循环;
e.printStackTrace();
}
System.out.println(“interrupt…”);
}
});
t1.start();
System.out.println(“默认t1 interrupt状态 ===>” + t1.isInterrupted());
Thread.sleep(2);
t1.interrupt();//发出中断申请;
System.out.println(“之后t1 interrupt状态01 ===>” + t1.isInterrupted());
}
代码2
public static void main(String[] args)
{
//测试当前线程是否被中断(检查中断标志),返回一个boolean并清除中断状态,
// 第二次再调用时中断状态已经被清除,将返回一个false。
System.out.println(Thread.currentThread().getName()+"\t"+Thread.interrupted());
System.out.println(Thread.currentThread().getName()+"\t"+Thread.interrupted());
System.out.println("----1");
Thread.currentThread().interrupt();// 中断标志位设置为true
System.out.println("----2");
System.out.println(Thread.currentThread().getName()+"\t"+Thread.interrupted());
System.out.println(Thread.currentThread().getName()+"\t"+Thread.interrupted());
LockSupport.park();
Thread.interrupted();//静态方法
Thread.currentThread().isInterrupted();//实例方法
}
代码3
public static void main(String[] args) {
System.out.println(Thread.interrupted());//线程默认中断状态为false.返回false并清除中断状态
Thread.currentThread().interrupt();//发出一个中断协商;中断状态由false–>true
System.out.println(Thread.currentThread().isInterrupted());//返回当前线程中断状态:true
System.out.println(Thread.interrupted());//返回当前线程中断状态并清除中断状态;true;
System.out.println(Thread.interrupted());//返回当前线程中断状态并清除中断状态;false;
}
结果: