/**
* 抛出InterruptedException异常的时候,要注意中断标志位
*/
public class HasInterruptException {
private static class UseThread extends Thread{
public UseThread(String name) {
super(name);
}
@Override
public void run() {
String threadName = Thread.currentThread().getName();
while(!isInterrupted()) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
System.out.println(threadName + " catch InterruptedException interruptFlag is " + isInterrupted());
interrupt();
}
System.out.println(threadName);
}
System.out.println(threadName + " interruptFlag is " + isInterrupted());
}
}
public static void main(String[] args) throws InterruptedException {
Thread endThread = new UseThread("HasInterruptEx");
endThread.start();
Thread.sleep(1000);
endThread.interrupt();
}
}
线程抛出InterruptedException,如何中断
最新推荐文章于 2021-03-05 06:30:23 发布
本文深入探讨了在Java中处理InterruptedException的方法,特别关注了中断标志位的重要性。通过一个具体示例,展示了如何在捕获异常后检查并重新设置中断状态,确保线程能够正确响应中断请求。
1765

被折叠的 条评论
为什么被折叠?



