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.
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.
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() .
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With