gpt4 book ai didi

java - 关于java中的中断

转载 作者:行者123 更新时间:2023-11-29 05:42:55 26 4
gpt4 key购买 nike

直接来自 this甲骨文教程:

Interrupts

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate. This is the usage emphasized in this lesson.

“由程序员决定..” 在哪里可以对特定行为进行编程?“线程终止很常见” 是否意味着标准行为终止线程?

编辑:例如,我们有来自 Sempaphore 类的 acquireUninterruptibly 方法,如果接收到中断,它只会延迟中断导致中断的等待时间。可能在这种情况下,中断处理仅包含一个 Thread.yield()? 提前致谢。

最佳答案

通常像 sleep 这样的方法会抛出 InterruptedException

如果线程长时间未调用抛出 InterruptedException 的方法?然后它必须定期调用 Thread.interrupted,如果已收到中断,则返回 true。例如:

for (int i = 0; i < inputs.length; i++) {
heavyCrunch(inputs[i]);
if (Thread.interrupted()) {
// We've been interrupted: no more crunching.
return;
}
}

在这个简单的示例中,代码只是测试中断并在收到中断时退出线程。在更复杂的应用程序中,抛出 InterruptedException 可能更有意义:

if (Thread.interrupted()) {
throw new InterruptedException();
}

现在回答您的问题:

  1. 从上面的例子可以看出,如果方法没有处理InterruptedException,你可以自己处理
  2. 由于您可以为这些方法处理此问题,因此您可以执行其他任务而不是退出。但是在中断发生后退出线程绝对是最常见的。

来源:javadoc

关于java - 关于java中的中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16871089/

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