Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isInterrupted() is not triggered

Experimenting with the interrupt(), found that the isInterrupted() is always false.

Another thing is that replacing the isInterrupted() with Thread.interrupted() will make the thread stop.

Could someone explain why this behavior occurs?

public static void main(String[] args) {
        Thread counter = new Thread(new Worker());
        counter.start();
        counter.interrupt();
    }

    static class Worker extends Thread {

        @Override
        public void run() {
            String msg = "It was interrupted"; 

            while (true) {
                if (isInterrupted()) {
                    System.out.println(msg);
                    return;
                }
            }
        }
    }
like image 360
IonKat Avatar asked Jan 30 '26 10:01

IonKat


2 Answers

You have two thread objects: Worker is a thread on its own, and you wrap it in a new separate Thread object:

Thread counter = new Thread(new Worker());

The two thread objects have two interrupt flags. Calling counter.interrupt() sets the interrupt flag in the outer thread object, while calling isInterrupted() checks the interrupt flag in the inner "Worker" thread object.

The reason why Thread.interrupted() makes the thread stop is because it checks the interrupt flag of the currently running thread which in this case will be the outer object.

It would be clearer code if you got rid of the outer thread object and wrote:

Worker counter = new Worker();
counter.start();
counter.interrupt();
like image 198
Joni Avatar answered Feb 01 '26 00:02

Joni


You should initialize your counter like that:

 Thread counter = new Worker();

Since Worker extends Thread but it is passed as Runnable, you have two different instances of Thread.

However Thread.interrupted() will interrupt the current thread, thus it works.

As an alternative to the above solution, replace isInterrupted() with Thread.currentThread().isInterrupted().

like image 27
Dorian Gray Avatar answered Jan 31 '26 23:01

Dorian Gray