我对 Java 中的线程比较陌生,我注意到每次使用 Thread.sleep() 时,我都必须捕获 InterrupetdException。
什么样的行为会导致这种情况,在我有监控线程的简单应用程序中,我可以忽略异常吗?
最佳答案
当有人调用 interrupt() 时会发生这种情况在线程上。 This article by Brian Goetz解释了中断机制以及应该如何处理 InterruptedExceptions:
"The most common response to InterruptedException is to swallow it -- catch it and do nothing (or perhaps log it, which isn't any better) -- as we'll see later in Listing 4. Unfortunately, this approach throws away important information about the fact that an interrupt occurred, which could compromise the application's ability to cancel activities or shut down in a timely manner."
"If you catch InterruptedException but cannot rethrow it, you should preserve evidence that the interruption occurred [...]. This task is accomplished by calling interrupt() to "reinterrupt" the current thread."
关于java - 什么样的行为会导致异常中断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/225194/