gpt4 book ai didi

java - 为什么中断方式和 isInterrupted 行为之间存在差异?

转载 作者:搜寻专家 更新时间:2023-11-01 02:57:33 25 4
gpt4 key购买 nike

我正在浏览 Javadoc for interrupts .我确实了解 Thread 类的两种方法之间的区别:interrupted() 和 isInterrupted()。引用文档:

When a thread checks for an interrupt by invoking the static method Thread.interrupted, interrupt status is cleared. The non-static isInterrupted method, which is used by one thread to query the interrupt status of another, does not change the interrupt status flag.

我不明白的是,为什么一直保持这种行为?interrupted 会重置当前线程的状态,而 isInterrupted 不会重置调用它的线程的状态,这有什么原因吗?

最佳答案

Thread.interrupted 只适用于当前线程;这是一个静态方法。

new Thread(() -> {
while (true) {
if (Thread.interrupted()) {
break;
}
System.out.println("Running");
}
});

清除标志很方便,因为执行检查的线程应该对中断使用react并以某种方式处理它。如果您想再次重置标志,那很简单:只需调用 interrupt


isInterrupted 不是静态方法。它被设计成可能被其他线程调用。

Thread foo = new Thread(/*...*/);
foo.start();

//...

if (foo.isInterrupted())
{
//do something
}

首先,其他线程在概念上不应该能够告诉 foo 它不再被中断。 foo 必须自己处理中断 - 其他线程不能代表 foo 处理。

从实现的角度来看,如果此方法要自动清除标志,则必须将此先检查后重置设置为原子操作,以避免线程 foo 在重置标志之前读取标志。您将不得不以某种方式与线程本身共享此互斥锁。这会使 isInterrupted 方法使用起来非常笨拙。

关于java - 为什么中断方式和 isInterrupted 行为之间存在差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50117219/

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