Java sleep 从主线程抛出 InterruptedException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2663419/
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
sleep from main thread is throwing InterruptedException
提问by Chris
I have the main thread of execution which spawns new threads. In the main thread of execution in main() I am calling Thread.sleep()
. When do I get an Unhandled exceptiontype InterruptedException
?.
我有产生新线程的主执行线程。在 main() 的主执行线程中,我正在调用Thread.sleep()
. 我什么时候会收到未处理的异常类型InterruptedException
?。
I am unsure of why am I getting this. I thought this was because I needed a reference to the main thread so I went ahead and made a reference to it via Thread.currentThread()
.
我不确定为什么我会得到这个。我认为这是因为我需要对主线程的引用,所以我继续并通过Thread.currentThread()
.
Is this not the way to have the thread sleep? What I need to do is have the main thread wait/sleep/delay till it does it required work again.
这不是让线程休眠的方法吗?我需要做的是让主线程等待/睡眠/延迟,直到它再次需要工作。
采纳答案by Eyal Schneider
What you see is a compilation error, due to the fact that you didn't handle the checked exception (InterruptedException
in this case) properly. Handling means doing one of the following:
您看到的是编译错误,因为您没有正确处理已检查的异常(InterruptedException
在本例中)。处理是指执行以下操作之一:
1) Declaring the method as throws InterruptedException
, thus requiring the caller to handle the exception
1) 将方法声明为throws InterruptedException
,从而要求调用者处理异常
2) Catching it with a try{..}catch(..){..}
block. For example:
2) 用try{..}catch(..){..}
块抓住它。例如:
try {
Thread.sleep(1500);
} catch(InterruptedException e) {
System.out.println("got interrupted!");
}
InterruptedException
is used to indicate that the current thread has been interrupted by an external thread while it was performing some blocking operation (e.g. interruptible IO, wait, sleep)
InterruptedException
用于指示当前线程在执行某些阻塞操作(例如可中断 IO、等待、睡眠)时被外部线程中断
回答by GuruKulki
Thread.sleep(t);
This is how you can make your thread wait. where t is in milliseconds. It is working fine in my main method, so to find out your problem it would be better if you can provide your code here.
这就是你如何让你的线程等待。其中 t 以毫秒为单位。它在我的主要方法中工作正常,所以如果你能在这里提供你的代码,找出你的问题会更好。
回答by ashutosh
At the line where you're definition of mainstarts, just include throws Exception. I too was facing similar problem, and this helped. After this inclusion, you need not include the Thread.sleep(xx);inside a try-catch statement
在定义main开始的那一行,只包含throws Exception。我也面临着类似的问题,这有帮助。在包含之后,您不需要包含Thread.sleep(xx); 在 try-catch 语句中