[英]InterruptedException: Is Thread.currentThread().interrupt() necessary as the interrupted flag is set
We all know that when catching an interruptedexception we are supposed to Thread.currentThread().interrupt();我们都知道,当捕获一个中断的异常时,我们应该使用 Thread.currentThread().interrupt();
However, from my tests, that flag is already set.但是,根据我的测试,该标志已经设置。
Thread t = new Thread(() -> {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
// Thread.currentThread().interrupt();
}
});
t.start();
System.out.println(t.isInterrupted());
t.interrupt();
System.out.println(t.isInterrupted());
Prints:印刷:
false
true
So what is the point of that commented out line?那么注释掉的那一行有什么意义呢?
If the line is commented out and you try to check in the thread itself if it is interrupted, you will get false as response.如果该行被注释掉并且您尝试检查线程本身是否被中断,您将得到错误作为响应。
Thread t = new Thread(() -> {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
// Thread.currentThread().interrupt();
}
System.out.println(Thread.currentThread().isInterrupted());//false
});
If you execute the line you get true.如果你执行这条线,你会得到真实的。
Thread t = new Thread(() -> {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println(Thread.currentThread().isInterrupted());//true
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.