Java 的 Thread.sleep 什么时候抛出 InterruptedException?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1087475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When does Java's Thread.sleep throw InterruptedException?
提问by Manki
When does Java's Thread.sleep throw InterruptedException? Is it safe to ignore it? I am not doing any multithreading. I just want to wait for a few seconds before retrying some operation.
Java 的 Thread.sleep 什么时候抛出 InterruptedException?忽略它是否安全?我没有做任何多线程。我只想等待几秒钟,然后再重试某些操作。
采纳答案by Brandon E Taylor
You should generally NOT ignore the exception. Take a look at the following paper:
您通常不应忽略异常。看看下面的论文:
Don't swallow interrupts
Sometimes throwing InterruptedException is not an option, such as when a task defined by Runnable calls an interruptible method. In this case, you can't rethrow InterruptedException, but you also do not want to do nothing. When a blocking method detects interruption and throws InterruptedException, it clears the interrupted status. If you catch InterruptedException but cannot rethrow it, you should preserve evidence that the interruption occurred so that code higher up on the call stack can learn of the interruption and respond to it if it wants to. This task is accomplished by calling interrupt() to "reinterrupt" the current thread, as shown in Listing 3. At the very least, whenever you catch InterruptedException and don't rethrow it, reinterrupt the current thread before returning.
public class TaskRunner implements Runnable { private BlockingQueue<Task> queue; public TaskRunner(BlockingQueue<Task> queue) { this.queue = queue; } public void run() { try { while (true) { Task task = queue.take(10, TimeUnit.SECONDS); task.execute(); } } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); } } }
不要吞下中断
有时抛出 InterruptedException 不是一种选择,例如当 Runnable 定义的任务调用可中断方法时。在这种情况下,您不能重新抛出 InterruptedException,但您也不想什么都不做。当阻塞方法检测到中断并抛出 InterruptedException 时,它会清除中断状态。如果您捕获 InterruptedException 但无法重新抛出它,您应该保留中断发生的证据,以便调用堆栈上的代码可以了解中断并在需要时对其进行响应。这个任务是通过调用 interrupt() 来“重新中断”当前线程来完成的,如清单 3 所示。至少,每当您捕获 InterruptedException 并且不重新抛出它时,在返回之前重新中断当前线程。
public class TaskRunner implements Runnable { private BlockingQueue<Task> queue; public TaskRunner(BlockingQueue<Task> queue) { this.queue = queue; } public void run() { try { while (true) { Task task = queue.take(10, TimeUnit.SECONDS); task.execute(); } } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); } } }
See the entire paper here:
在此处查看整篇论文:
http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html?ca=drs-
http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html?ca=drs-
回答by starblue
A solid and easy way to handle it in single threaded code would be to catch it and retrow it in a RuntimeException, to avoid the need to declare it for every method.
在单线程代码中处理它的可靠且简单的方法是捕获它并在 RuntimeException 中追溯它,以避免需要为每个方法声明它。
回答by Brian Agnew
The Java Specialists newsletter (which I can unreservedly recommend) had an interesting article on this, and how to handle the InterruptedException
. It's well worth reading and digesting.
Java 专家时事通讯(我可以毫无保留地推荐)对此有一篇有趣的文章,以及如何处理InterruptedException
. 非常值得阅读和消化。
回答by BrutalOst
The InterruptedException
is usually thrown when a sleep is interrupted.
在InterruptedException
当睡眠被中断通常是抛出。
回答by Christian
If an InterruptedException
is thrown it means that something wants to interrupt (usually terminate) that thread. This is triggered by a call to the threads interrupt()
method. The wait method detects that and throws an InterruptedException
so the catch code can handle the request for termination immediately and does not have to wait till the specified time is up.
如果 anInterruptedException
被抛出,则意味着有些东西想要中断(通常是终止)该线程。这是由调用线程interrupt()
方法触发的。wait 方法检测到并抛出一个,InterruptedException
因此捕获代码可以立即处理终止请求,而不必等到指定的时间结束。
If you use it in a single-threaded app (and also in some multi-threaded apps), that exception will never be triggered. Ignoring it by having an empty catch clause I would not recommend. The throwing of the InterruptedException
clears the interrupted state of the thread, so if not handled properly that info gets lost. Therefore I would propose to run:
如果您在单线程应用程序(以及一些多线程应用程序)中使用它,则永远不会触发该异常。我不建议通过使用空的 catch 子句来忽略它。抛出InterruptedException
清除线程的中断状态,因此如果处理不当,信息就会丢失。因此,我建议运行:
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
// code for stopping current task so thread stops
}
Which sets that state again. After that, finish execution. This would be correct behaviour, even tough never used.
这再次设置了该状态。之后,完成执行。这将是正确的行为,甚至从未使用过。
What might be better is to add this:
可能更好的是添加以下内容:
} catch (InterruptedException e) {
throw new RuntimeException("Unexpected interrupt", e);
}
...statement to the catch block. That basically means that it must never happen. So if the code is re-used in an environment where it might happen it will complain about it.
...catch 块的语句。这基本上意味着它绝不能发生。因此,如果代码在可能发生的环境中重复使用,它会抱怨它。
回答by Anshika
Methods like sleep()
and wait()
of class Thread
might throw an InterruptedException
. This will happen if some other thread
wanted to interrupt the thread
that is waiting or sleeping.
像sleep()
and wait()
of class这样的方法Thread
可能会抛出一个InterruptedException
. 如果其他人thread
想要打断thread
正在等待或睡眠的对象,就会发生这种情况。