Why does Thread.isInterrupted () always return false?
I found the method of JavaDoc:
Returns: true if this thread has been interrupted; false otherwise.
开发者_StackOverflow社区I think something wrong with my understanding of the method. Further, I may misunderstand the concept ‘interrupt’ in Thread.
Any explanation is welcome! Thank you!
Code snippet:
In thread definition:
public void run() {
try {
//Do something
} catch (InterruptedException e) {
System.out.println(isInterrupted());//Always false
return;
}
}
invoke:
theThread.interrupt();
This behaviour is typically documented in methods that throw that exception. For example, the javadoc for Object.wait()
says:
"
InterruptedException
- if any thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown."
Indeed, the javadoc for the exception itself says this:
"Occasionally a method may wish to test whether the current thread has been interrupted, and if so, to immediately throw this exception. The following code can be used to achieve this effect:
if (Thread.interrupted()) // Clears interrupted status! throw new InterruptedException();
Note how they emphasize that the flag should be cleared before the exception is thrown.
Why was it designed to work like this? You'd have to ask the designers, but I expect they figured that an exception handler should handle the situation, and that there should therefore be no need for the flag to still be set at that point. (If the handler doesn't fully handle the situation it can either rethrow the exception, or call Thread.getCurrentThread.interrupt()
to set the flag again.)
Once the exception is thrown, the thread is no longer in an interrupted state.
Adding to cdhowie's answer, one standard pattern is to let the Thread handle interruption. This is useful with Executors, when the running code doesn't "own" the Thread and should not get in the way of interruption (unless you really know what you're doing)
public void run() {
try {
//Do something
} catch (InterruptedException e) {
// Do whatever local clean up you need to
...
// Then let the owning Thread know it's been interrupted, so it too can clean up
Thread.currentThread().interrupt(); //
}
}
You would check isInterrupted() in your own code, for example from a loop. If the thread has been interrupted you can then throw InterruptedException to stop executing.
In your example if you caught InterruptedException you can be sure that it was interrupted and you don't have to check that method.
精彩评论