开发者

sleep from main thread is throwing InterruptedException

开发者 https://www.devze.com 2022-12-27 02:27 出处:网络
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 exception type 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(). When do I get an Unhandled exception type 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().

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. Handling means doing one of the following:

1) Declaring the method as throws InterruptedException, thus requiring the caller to handle the exception

2) Catching it with a try{..}catch(..){..} block. 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 (e.g. interruptible IO, wait, sleep)


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); inside a try-catch statement


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号