The Java documentation is not clear on this point. What happens if you call interrupt on a Thread before a call to Thread.sleep():
//interrupt reaches Thread here
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
return;
}
Will the InterruptedException be thrown?
Please point to relevant documentation.
A thread that is in the sleeping or waiting state can be interrupted with the help of the interrupt() method of Thread class.
Thread. sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.
Threads can be interrupted, and when a thread is interrupted, it will throw InterruptedException. In the next sections, we'll see InterruptedException in detail and learn how to respond to it.
Yes, it will throw an exception. According to the javadoc for Thread.sleep, the method:
Throws: InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.
The 'has' in this case is an informal way of referring to the interrupted status. It's a shame that it is informal - if there's somewhere a spec should be precise and unambiguous, well, it's everywhere, but it's the threading primitives above all.
The way the interrupted status mechanism works in general is if that a thread receives an interruption while it's not interruptible (because it's running), then the interruption is essentially made to wait until the thread is interrupted, at which point it swoops in an causes an InterruptedException. This is an example of that mechanism.
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