interrupt()函数的本质是将中断位置的boolean的值设置为true,表示处在中断状态,在中断状态下执行sleep(),wait(),join()则会出现中断异常,抛出异常之后,中断状态为false,在false的状态下,执行以上阻塞方法则不会抛出中断异常。
public class Test extends Thread {
public static void main(String[] args){
Test t = new Test();
t.start();
}
public void run(){
try {
sleep(2000);
interrupt();
System.out.println("11111");
} catch (InterruptedException e) {
System.out.println("11111出现中断异常");
}
System.out.println(Thread.currentThread().isInterrupted());
try {
sleep(2000);
System.out.println("22222");
} catch (InterruptedException e) {
System.out.println("22222出现中断异常");
}
System.out.println(Thread.currentThread().isInterrupted());
try {
System.out.println("sleep33333");
// interrupt();
sleep(2000);
System.out.println("33333");
} catch (InterruptedException e) {
System.out.println("33333出现中断异常");
}
System.out.println(Thread.currentThread().isInterrupted());
}
}
Interrupt() : 将中断标志设置为true,发送一个中断状态的信号;
interrupted() : 返回当前的中断状态,然后再将中断状态重置为false,即没有中断;
isInterrupted() : 返回当前中断状态