Search code examples
multithreadingthread-sleep

Execution of a thread after it got interrupted


A thread is executing task to print numbers from 0 to n, and sleeps for 4000 ms after every print statement. Somewhere in the middle thread gets interrupted. Now when the same thread starts its execution, where will it start from , will it start printing the numbers from 0 to n again, or it will print numbers from where it got interrupted. In both cases what are the reasons and how it is being handled?


public class Main {

    public static void main(String[] args) throws InterruptedException {
   
        SleepTest sleepTest = new SleepTest();
        Thread thread = new Thread(sleepTest);
        thread.start();
        thread.interrupt();

    }
}
public class SleepTest implements Runnable{
static int sleep = 10;
    public void run(){
        for (int i =0; i<10; i++){
           System.out.println(i);

            try {
                Thread.currentThread().interrupt();
              Thread.sleep(4000);

            } catch (InterruptedException exception) {

                exception.printStackTrace();

            }
            System.out.println(Thread.interrupted());
        }
    }


Solution

  • Calling a interrupt() on a thread object can only suggest thread to stop. It is not guarantee that the thread will stop.
    It completely depends on the implementation of run() method of thread.

    In your case in run() you are catching the InterruptedException and you are printing the exception trace but not stopping the thread. Thats why thread will never stop on InterruptedException and continue the execution.
    It may look like thread is getting stopped(by seeing exception trace) when see the output on console.

    Refer interrupt interrupted isinterrupted in Java