Java 线程休眠和中断异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15528140/
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
Java Thread Sleep and Interrupted Exception
提问by Jericho Aganon
- Why does a sleep thread need a try catch to catch Interrupted Exception?
- Why does a sleep even emit an Interrupted Exception error? This are the two questions I really wanna find out about in java programming I've been searching through google and i've still haven't found a clear explanation is to why this two things happen.
- 为什么睡眠线程需要 try catch 来捕获中断的异常?
- 为什么 sleep 甚至会发出中断的异常错误?这是我在 Java 编程中真正想知道的两个问题,我一直在通过谷歌搜索,但我仍然没有找到明确的解释来解释为什么会发生这两件事。
采纳答案by jsedano
1.- Because a Thread cant complete its normal execution if you Interrupt it, and you need to catch that in order to be prepared to do something. 2.- Because a thread waiting is different from an interrupted thread, a thread waiting can be resumed, but an interrupted thread is already finish execution.
1.- 因为如果您中断线程,线程将无法完成其正常执行,并且您需要捕获它以准备做某事。2.- 因为等待的线程与被中断的线程不同,等待的线程可以恢复,但被中断的线程已经完成执行。
回答by Javier
An InterruptedException
is thrown when the thread is blocked/waiting and it is interrupted by another thread (by means of Thread.interrupt
). Think of it as a request for immediate termination, that do not suffer the drawbacks of Thread.stop()
.
一个InterruptedException
当线程被阻塞,则抛出/等待,它是由另一个线程中断(借助Thread.interrupt
)。将其视为立即终止的请求,不会受到Thread.stop()
.
This way, even if you instruct a thread to sleep for several years, you are able to interrupt that thread.
这样,即使您指示一个线程休眠数年,您也可以中断该线程。
The recommended practiceis aborting whatever you are processing when a InterruptedException
is thrown.
推荐的做法是在InterruptedException
抛出a 时中止正在处理的任何内容。
回答by vishnu viswanath
When you ask a thread to sleep, the expected behavior for that thread is to sleep for that much time. So if the sleep is interrupted, it will throw InterruptedException to indicate that it couldn't complete the task. And you might want to take care of what should be done if it is Interrupted.
当您要求一个线程休眠时,该线程的预期行为是休眠那么多时间。所以如果sleep被打断了,就会抛出InterruptedException,表示无法完成任务。如果它被中断,您可能想要处理应该做什么。
回答by Evgeni Sergeev
Sleep and interrupts are not related semantically. It's just that Java designers thought that when you want your thread to sleep, it's a good opportunity to remind you about interrupts. This is like Dukesaying "It looks like you're trying to sleep, would you also like to make your thread a good citizen by making sure that it responds to interrupt events properly, when the need for a way to get it to terminate abruptly at a later stage in your project arises?"
睡眠和中断在语义上没有关系。只是 Java 设计者认为,当您希望线程休眠时,这是提醒您有关中断的好机会。这就像杜克说的“看起来你正在尝试睡觉,你是否也想让你的线程成为一个好公民,通过确保它正确响应中断事件,当需要一种方法让它突然终止时在你的项目后期出现?”
So one will often see code like this:
所以经常会看到这样的代码:
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
//Don't worry about it.
}
Sometimes people say this is considered bad practice. But if you're not planning to use the interrupts facility in your program, then these exceptions will never be thrown, so you have to ask yourself whether doing the extra work in order to take care of these exceptions, in case you decide to add the interruptibility feature to your program some time later, makes sense. This is one of those things that Java designers insisted that every thread should do — that you could interrupt()
it, and it will quickly and cleanly abort what it's doing. I think that's unnecessary in many cases, but people will look at your code, see this and still say "eew, bad practice!"
有时人们说这被认为是不好的做法。但是如果你不打算在你的程序中使用中断设施,那么这些异常将永远不会被抛出,所以你必须问自己是否做了额外的工作来处理这些异常,以防你决定添加一段时间后,您的程序的可中断功能是有道理的。这是 Java 设计者坚持每个线程都应该做的事情之一——你可以interrupt()
做到,并且它会快速而干净地中止它正在做的事情。我认为在很多情况下这是不必要的,但是人们会查看您的代码,看到这一点仍然会说“呃,糟糕的做法!”
The official Java tutorial explains interrupts. Basically, if you have one thread t
doing some processing, and then the user wants to cancel it, from another thread you would call t.interrupt()
. In the code that's running on thread t
, whenever it sleep()
s, or wait()
s, etc., an InterruptedException
will be thrown. If it doesn't do any of these, then it can (should) also find out if it had been interrupted using Thread.interrupted()
from time to time. In all these ways of finding out about interrupts, it should abandon what it's doing and clean up ASAP. (That is to say: if it does so, then this behaviour might be useful to you or someone — that's the idea of interrupts.)
官方 Java 教程解释了中断。基本上,如果你有一个线程t
在做一些处理,然后用户想要取消它,你会从另一个线程调用t.interrupt()
. 在线程上运行的代码中t
,每当它sleep()
s 或wait()
s 等时,InterruptedException
都会抛出an 。如果它不做任何这些,那么它也可以(应该)找出它是否被Thread.interrupted()
不时中断使用。在所有这些发现中断的方法中,它应该放弃它正在做的事情并尽快清理。(也就是说:如果它这样做了,那么这种行为可能对你或某人有用——这就是中断的想法。)
So, Java makes this a checked exception of the sleep(..)
method, to force you to think about using this facility. The other part of the rationale is that ifsleep(..)
is interrupted, then it will wake up early, and that's an exceptional event. (But remember, there's that "if".)
因此,Java 将其sleep(..)
设为该方法的已检查异常,以迫使您考虑使用此功能。理由的另一部分是,如果sleep(..)
被打断,那么它会提前醒来,这是一个例外事件。(但请记住,还有“如果”。)
The important thing is that interrupts don't just happen for no reason. They happen if you write code to make them happen, or if someone else does, who launches your threads and has a need to cancel their activities. So this is who causes Thread.sleep(..)
to throw an InterruptedException
. You do. And if you don't, then you still need to catch it.
重要的是,中断不会无缘无故地发生。如果您编写代码来实现它们,或者如果其他人启动了您的线程并需要取消他们的活动,它们就会发生。所以这就是导致Thread.sleep(..)
抛出InterruptedException
. 你做。如果你不这样做,那么你仍然需要抓住它。
Edit.By the way, it would be a better practice to do it this way:
编辑。顺便说一句,这样做会是一个更好的做法:
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
throw new UnsupportedOperationException("Interrupts not supported.", ie);
}
So, if you, or somebody else, ever tries to interrupt this thread by mistake later, then when they go to test it, they will be reminded that this feature is not implemented. (UnsupportedOperationException
is a subclass of RuntimeException
, so it's unchecked.)
因此,如果您或其他人稍后尝试错误地中断此线程,那么当他们去测试时,他们将被提醒该功能未实现。(UnsupportedOperationException
是 的子类RuntimeException
,因此未选中。)
回答by Benj
There is a clean example of how the Interrupted Exception can be thrown here : http://www.javamex.com/tutorials/threads/thread_interruption.shtml
这里有一个关于如何抛出中断异常的干净示例:http: //www.javamex.com/tutorials/threads/thread_interruption.shtml
And a discuss about sleep()
and yield()
here : http://www.coderanch.com/t/508657/threads/java/Sleep-Yield-state
和讨论有关sleep()
与yield()
此:http://www.coderanch.com/t/508657/threads/java/Sleep-Yield-state
回答by James
It's because sleep()
could potentially block forever/a long time so you need a way to be able to cancel this behaviour. Because it is not "normal" completion when you interrupt the action you may need to perform some specific compensating or remedial action, e.g., to send an alert that you never received a notification, clean up resources, etc.
There is a pretty good developer works article on the subject.
这是因为sleep()
可能会永久/长时间阻塞,因此您需要一种能够取消此行为的方法。因为当您中断操作时它不是“正常”完成,您可能需要执行一些特定的补偿或补救操作,例如,发送您从未收到通知的警报,清理资源等。
有一个非常好的开发人员关于这个主题的作品文章。