gpt4 book ai didi

java Thread#isInterrupt 对于死线程总是返回 false

转载 作者:行者123 更新时间:2023-11-30 06:26:32 26 4
gpt4 key购买 nike

我遇到了奇怪的行为。所有消息来源都表明,在捕获中断异常后,您需要调用 Thread.currentThread().interrupt() 来恢复中断标志。但我尝试创建简单的应用程序,在进程中断后检查中断状态

public class Main {
public static void main(String[] args) throws InterruptedException {
Runnable r = () -> {
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
System.out.println("interrupted exception is occurred");
Thread.currentThread().interrupt();
System.out.println("interrupt flag is updated:" + Thread.currentThread().isInterrupted());
}
};

Thread thread = new Thread(r);
thread.start();
thread.interrupt();

boolean interruptFlag;
do {
Thread.sleep(1000);
interruptFlag = thread.isInterrupted();
System.out.println("interrupt flag:" + interruptFlag + " isAlive:" + thread.isAlive());
} while (!interruptFlag);
}
}

如果你尝试运行它,那么你会得到

interrupted exception is occurred
interrupt flag is updated:true
interrupt flag:false isAlive:false
interrupt flag:false isAlive:false
interrupt flag:false isAlive:false
interrupt flag:false isAlive:false
interrupt flag:false isAlive:false

它将无限地工作。问题是为什么线程死后,iterrupt flag 为 false?

最佳答案

当您从主线程检查中断状态时,第二个线程已经死亡,因此它返回 false。尝试将 Thread.sleep(1000) 放在等待循环的末尾,您将在中断状态中看到 true。

此行为没有记录,因此很难说它是缺乏文档还是现有实现的功能。私有(private)原生 boolean isInterrupted(boolean ClearInterrupted) 的实现;方法需要检查才能说得更多。

类似讨论:Thread.isInterrupted() returns false after thread has been terminated

关于java Thread#isInterrupt 对于死线程总是返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47091907/

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