Java question: As far as I know, there are two ways to check inside a thread whether the thread received an interrupt signal, Thread.interrupted()
and Thread.isInterrupted()
, and the only difference between them is that the former resets the internal interrupted flag.
So far, I've always used Thread.isInterrupted()
and never had any problems with it. Then again, most tutorials I've seen recommend using Thread.interrupted()
. Is there any specific reason for that?
By calling Thread. currentThread(). interrupt() , you set the interrupt flag of the thread, so higher-level interrupt handlers will notice it and can handle it appropriately.
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.
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.
interrupted()
is static
and checks the current thread. isInterrupted()
is an instance method which checks the Thread
object that it is called on.
A common error is to call a static method on an instance.
Thread myThread = ...; if (myThread.interrupted()) {} // WRONG! This might not be checking myThread. if (myThread.isInterrupted()) {} // Right!
Another difference is that interrupted()
also clears the status of the current thread. In other words, if you call it twice in a row and the thread is not interrupted between the two calls, the second call will return false
even if the first call returned true
.
The Javadocs tell you important things like this; use them often!
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