简体   繁体   English

从主线程休眠是抛出InterruptedException

[英]sleep from main thread is throwing InterruptedException

I have the main thread of execution which spawns new threads. 我有执行的主线程产生新线程。 In the main thread of execution in main() I am calling Thread.sleep() . 在main()的主要执行线程中,我调用Thread.sleep() When do I get an Unhandled exception type InterruptedException ?. 我什么时候得到Unhandled异常类型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. 我需要做的是让主线程等待/睡眠/延迟,直到它再次需要工作。

What you see is a compilation error, due to the fact that you didn't handle the checked exception ( InterruptedException in this case) properly. 您看到的是编译错误,因为您没有正确处理已检查的异常(在这种情况下为InterruptedException )。 Handling means doing one of the following: 处理意味着执行以下操作之一:

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. 2)使用try{..}catch(..){..}块来捕获它。 For example: 例如:

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 (eg interruptible IO, wait, sleep) InterruptedException用于指示当前线程在执行某些阻塞操作时被外部线程中断(例如,可中断IO,等待,休眠)

At the line where you're definition of main starts, just include throws Exception . 在您定义主要开始的行,只包括抛出异常 I too was facing similar problem, and this helped. 我也面临类似的问题,这有帮助。 After this inclusion, you need not include the Thread.sleep(xx); 包含此内容后,您不需要包含Thread.sleep(xx); inside a try-catch statement 在try-catch语句中

Thread.sleep(t);

This is how you can make your thread wait. 这是你如何让你的线程等待。 where t is in milliseconds. 其中t以毫秒为单位。 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. 它在我的主要方法中工作正常,所以要找出你的问题,如果你能在这里提供你的代码会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM