gpt4 book ai didi

java - 捕捉到 "InterruptedException"后,为什么 "Thread.currentThread().isInterrupted()"的值为 false?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:35:17 24 4
gpt4 key购买 nike

作为标题。

public static void main(String[] args) throws InterruptedException {

Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println(Thread.currentThread().isInterrupted()); //print false, who reset the interrupt?

}
}
});

thread.start();
TimeUnit.SECONDS.sleep(1);
thread.interrupt();
}

捕获“InterruptedException”后,为什么“Thread.currentThread().isInterrupted()”的值为false?

最佳答案

来自 Thread.sleep 的 Javadoc (由 TimeUnit.sleep 调用):

InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

我认为 isInterrupted() 的目的是让您检测线程是否在 调用会抛出 InterruptedException 的东西之前被中断>。如果您捕获InterruptedException,则可以公平地假设线程被中断...

关于java - 捕捉到 "InterruptedException"后,为什么 "Thread.currentThread().isInterrupted()"的值为 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9901649/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com