2
    Thread t = new Thread(){
        public void run(){
            while(true){

            }
        }
    };

    t.start();

    t.interrupt();
    System.out.println(t.interrupted());

I'm having an issue where I'm calling an interrupt on a thread and then check if a thread is interrupted - it always returns false. Why?

user2871354
  • 530
  • 1
  • 5
  • 15

2 Answers2

3

From the Java Thread docs (my italics):

static boolean interrupted(): Tests whether the current thread has been interrupted.

It's actually a static method(a) meant to be used in the target thread to see if someone has interrupted it, hence you would use it within t.run() itself.

The thread can also be notified by an InterruptedException if they happen to call a method that throws that exception, such as Thread.sleep().

And, as per that link above, in the detailed description of Thread.interrupted(), the way a thread clears its own interrupt status is by calling it:

The interrupted status of the thread is cleared by this method.


To test if a different thread has been interrupted, use the non-static isInterrupted():

boolean isInterrupted(): Tests whether this thread has been interrupted.


(a) I've often thought it would be a good idea if the compiler would warn you if you invoke a static (class-level) method on a specific object. I've seen a few occurrences where people have been bitten by similar issues.

But then I think, why? People using a language should understand the language, even the deep dark corners of it, C (for example) has quite a few of these :-)

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
1

interrupted() is a static method, it is called on current thread, try t.isInterrupted()

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275