DarkLeafyGreen
DarkLeafyGreen

Reputation: 70416

What happens after a thread is paused with sleep?

I have following code

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

Is the InterruptedException thrown when the thread has finished sleeping or when interrupt method is called on that thread?

Upvotes: 0

Views: 960

Answers (3)

rurouni
rurouni

Reputation: 2445

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.

Upvotes: 2

MByD
MByD

Reputation: 137352

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.

Upvotes: 3

BertNase
BertNase

Reputation: 2414

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.

Upvotes: 5

Related Questions