开发者

What happens after a thread is paused with sleep?

I have following code

try{
    sleep(500);
}catch(InterruptedException e){}

Is the Interrup开发者_开发知识库tedException thrown when the thread has finished sleeping or when interrupt method is called on that thread?


no, InterruptedException is not thrown during normal flow, but might happen when interrupt() is called on the thread (e.g. by some other code trying to interrupt normal execution flow of this thread). Normally execution simply continues in the line after the sleep statement.


If the interrupt method is called during the sleep time. The catch is relevant only for the code of try, after that it has no effect.


InterruptedException is throw if the Thread is interrupted which may happen during the sleep or which might have happened a while ago. In most cases when you do not expect the InterruptedException and don't want to handle it it ist better to

try{
    sleep(500);
}catch(InterruptedException e){
    Thread.currentThread().interrupt();
}

so the interrupt is not lost.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜