Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(). 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.

like image 868
Chris Avatar asked Apr 18 '10 18:04

Chris


People also ask

What causes an InterruptedException?

Class InterruptedException. Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity. Occasionally a method may wish to test whether the current thread has been interrupted, and if so, to immediately throw this exception.

How do I resolve InterruptedException?

By convention, any method that exits by throwing an InterruptedException clears the interrupt status of the calling thread. And it is always possible to set the interrupt status afterwards, by another thread invoking Thread. interrupt() .

Why does thread sleep threw an exception?

Method Whenever Thread. sleep() functions to execute, it always pauses the current thread execution. If any other thread interrupts when the thread is sleeping, then InterruptedException will be thrown.

Which methods in thread class throws an InterruptedException?

When the thread is executing the sleep() , wait() , and join() methods, those methods will throw an InterruptedException. Otherwise, a flag is set that the thread can examine to determine that the interrupt() method has been called.


1 Answers

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)

like image 108
Eyal Schneider Avatar answered Oct 18 '22 20:10

Eyal Schneider