阻塞方法(即sleep、wait方法)抛出InterruptedException中断一场后,如果要继续中断,需要手动中断一次,如果不手动中断,线程机会一直停在那里
public class EndThreadException extends Thread {
public EndThreadException(String name) {
super(name);
}
@Override
public void run() {
while (!isInterrupted()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName()+" 中断一场的中断标志位是:"+ isInterrupted());
//释放资源,如果这里不手动中断,线程将一直保持运行状态,浪费资源
interrupt();
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+" 中断标志位是 "+isInterrupted());
}
public static void main(String[] args) throws InterruptedException {
Thread thread = new EndThreadException(" hasInterruptEx");
thread.start();
Thread.sleep(500);
thread.interrupt();
}
}
加上手动中断
//资源释放
interrupt();
结果:
hasInterruptEx 中断一场的中断标志位是:false
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.example.demo.test.base.EndThreadException.run(EndThreadException.java:16)
hasInterruptEx 中断标志位是 true
Process finished with exit code 0
不使用interrupt();再次中断之后的结果