Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Thread.isInterrupted () always return false?

I found the method of JavaDoc:

Returns: true if this thread has been interrupted; false otherwise.

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(); 
like image 546
卢声远 Shengyuan Lu Avatar asked Aug 22 '11 02:08

卢声远 Shengyuan Lu


2 Answers

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.)

like image 104
Stephen C Avatar answered Oct 08 '22 14:10

Stephen C


Once the exception is thrown, the thread is no longer in an interrupted state.

like image 42
cdhowie Avatar answered Oct 08 '22 13:10

cdhowie