I understand perfectly what it does (at least I hope so). It doesn't really interrupt the thread. It makes Thread.isInterrupted()
true, and the code is supposed to check what method and stop the thread itself.
My question is, why do we even need this method? It seems perfectly replaceable by declaring a boolean flag stating whether this thread should be stopped? Doesn't any Java textbook use this boolean flag as the best example of how volatile
keyword should be used?
I am particularly confused, as there seems to be no way to "uninterrupt" the thread, as Thread.resume()
is deprecated. That makes interrupt()
even less useful than a boolean flag I write by myself.
Other than being perhaps a bit easier to write, does Thread.interrupt()
do anything different from my boolean flag?
An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.
In this state, a thread is waiting for a signal from another thread. When a thread either finishes execution or terminates abnormally, it'll wind up in the TERMINATED state. Threads can be interrupted, and when a thread is interrupted, it will throw InterruptedException.
Calling Thread. interrupt() is a way to tell the thread to stop what it is doing. If the thread is in a blocking call, the blocking call will throw an InterruptedException, otherwise the interrupted flag of the thread will be set. A Thread or a Runnable that is interruptible should check from time to time Thread.
interrupted() method is a static method of class thread checks the current thread and clear the interruption "flag". i.e. a second call to interrupted() will return false. isInterrupted() method is an instance method; it reports the status of the thread on which it is invoked. it does not clear the interruption flag.
From a related post:
Thread.interrupt() sets the interrupted status/flag of the target thread. Then code running in that target thread MAY poll the interrupted status and handle it appropriately. Some methods that block such as Object.wait() may consume the interrupted status immediately and throw an appropriate exception (usually InterruptedException)
From javadocs
Many methods that throw InterruptedException, such as sleep, are designed to cancel their current operation and return immediately when an interrupt is received.
By convention, any method that exits by throwing an InterruptedException clears interrupt status when it does so. However, it's always possible that interrupt status will immediately be set again, by another thread invoking interrupt.
So it provides more functionality rather than simply setting a boolean flag.
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