gpt4 book ai didi

java - 我希望我的线程处理中断,但我无法捕获 InterruptedException,因为它是一个已检查的异常

转载 作者:行者123 更新时间:2023-12-01 14:04:53 27 4
gpt4 key购买 nike

我在 Java 中有一个线程调用

t.interrupt();

使 t(不同的线程)被中断。我希望“t”线程然后捕获 InterruptedException但 Eclipse 不允许我放 InterruptedException说它没有被扔进 try 体内。我如何获得 InterruptedException被称为?我在用 t.interrupt()错误的?

最佳答案

我真的不喜欢接受的答案,所以我想我会投入 0.02 美元。

I want the "t" thread to then catch an InterruptedException but Eclipse won't let me put an InterruptedException in saying it's not thrown in the try body. How can I get the InterruptedException to be called? Am I using t.interrupt() wrong?


重要的是要意识到 t.interrupt()只在线程中设置中断位——它实际上并不中断线程的处理本身。线程可以随时安全地中断。
引自 Thread.interrupt() javadocs :
  • If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.

  • If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a java.nio.channels.ClosedByInterruptException.

  • If this thread is blocked in a java.nio.channels.Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.

  • If none of the previous conditions hold then this thread's interrupt status will be set.


重要的是要补充一点,如果线程的中断位已设置,然后 wait() (和其他人)被调用,然后 wait()会抛出 InterruptedException立即地。
所以你抓不到 InterruptedExeption无处不在,因为只有某些方法会抛出它。如果您想查看线程是否已被中断(再次设置了中断位),那么正确的做法是直接使用 Thread.getCurrentThread().isInterrupted() 对其进行测试。 .通常,我们会执行以下操作:
while (!Thread.getCurrentThread().isInterrupted()) {
// process stuff
...
try {
// here's an example of a method that throws InterruptedException
Thread.sleep(100);
} catch (InterruptedException e) {
// catching InterruptedException actually clears the interrupt bit
// so it is a good pattern to re-interrupt the thread immediately
Thread.currentThread().interrupt();
// now we decide what to do since we are interrupted
break;
}
}
关于这个主题有很多很好的问题和答案:
  • What does java.lang.Thread.interrupt() do?
  • How exactly does Thread.interrupt() and Thread.interrupted() work?
  • How to stop uninterruptible threads in Java
  • 关于java - 我希望我的线程处理中断,但我无法捕获 InterruptedException,因为它是一个已检查的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17840238/

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