Hemlata Hemlata - 26 days ago 9
Java Question

How a interrupted thread is starting again

Here is my following code:

public static void main(String[] args) throws InterruptedException {

System.out.println("Started");

Thread t = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 5; i++) {
try {
if (!Thread.currentThread().isInterrupted()) {
Thread.sleep(4000);
System.out.println("Inside run ");
}
} catch (InterruptedException e) {
System.out.println("Run is interrupted! ");
}
}
}
});

t.start();
Thread.sleep(2000);

t.interrupt();
t.join();

System.out.println("Finished");

}


Here's my output:

Started
Run is interrupted!
Inside run
Inside run
Inside run
Inside run
Finished


Here, I'm starting a thread by calling
t.start()
and then calling
Thread.sleep()
, So my main thread can sleep for 2000ms, then I'm calling
t.interrupt()
.


  • When I call
    t.interrupt
    the thread should be interrupted, right? But how it is starting again?

  • Is my thread starting again, without calling
    t.start()
    cause I'm calling
    t.join()
    after the thread is interrupted?


Answer

try catch block inside for loop, handles the exception. Once a Thread is interrupted, and InterruptedException is thrown, interrupt flag is set false again.

refer Methods that Clear the Thread.interrupt() flag

For ending the loop, you can set the interrupt flag as true from inside the catch block or can simply put the try catch block outside of the for loop. The first way will only work if in the loop you are checking for the interrupt flag.

Comments