Search code examples
javamultithreadinginterruptinterruption

Does a thread need to be in a RUNNABLE state before it can be interrupted?


Is it necessary for a thread in java to be in ready state before it gets interrupted by interrupt method? I tried to check this by typing the above given code below.

class MyThread extends Thread
{
    public void run() {
        try
        {
            for(int i =0;i<10;i++) {
               System.out.println("I am lazy thread");
               Thread.sleep(2000);
            }
        }
        catch(InterruptedException e) {
            System.out.println("I got interrupted");
        }
    }
}

public class SleepAndInterruptDemonstrationByDurga {
    public static void main(String[] args) {
       MyThread t= new MyThread();
       t.start();
       t.interrupt();
       System.out.println("End of main thread");
    }
}

The output what I got was always was the below one even after trying many times

End of main thread
I am lazy thread
I got interrupted

Why can't the output be

I am lazy thread
I got interrupted
End of main thread

as according to the code it can be seen that the interrupt method is called first by the main thread. Ultimately I want to ask that are there any situations possible when at first the interrupt call is executed before the the thread got started?


Solution

  • What happens here is

    1) the thread you start needs time to get ready to run, so “end of main thread” is probably going to print first, though that’s not guaranteed.

    2) the interrupt flag is set before the new thread is done starting, but nothing checks the status of that flag until the thread sleeps. When you call interrupt on a thread that only sets the flag, the thread doesn’t do anything to respond unless you put in calls to things like sleep or isInterrupted. So “I am lazy Thread” will show up before “I got interrupted”.

    Interruption is voluntary and requires the cooperation of the interrupted thread. The thread can’t act on the interrupt flag status until it is running, because some code has to check the flag and act on it.