Java: Difference in usage between Thread.interrupted() and Thread.isInterrupted()?
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 use interrupted
, what you're asking is "Have I been interrupted since the last time I asked?"
isInterrupted
tells you whether the thread you call it on is currently interrupted.