Java Thread Tutorial - Java Thread Interrupt








We can interrupt a thread that is alive by using the interrupt() method.

This method invocation on a thread is just an indication. It is up to the thread how it responds to the interruption.

Example

The following code shows the code that interrupts the main thread and prints the interrupted status of the thread.

public class Main {
  public static void main(String[] args) {
    System.out.println("#1:" + Thread.interrupted());
/*from   w  w w.  j  a  v  a2 s . c o  m*/
    // Now interrupt the main thread
    Thread.currentThread().interrupt();

    // Check if it has been interrupted
    System.out.println("#2:" + Thread.interrupted());

    // Check again if it has been interrupted
    System.out.println("#3:" + Thread.interrupted());
  }
}

The code above generates the following result.





Example 2

The following code how one thread will interrupt another thread.

public class Main {
  public static void main(String[] args) {
    Thread t = new Thread(Main::run);
    t.start();//  w w w.j  a  va  2s. c  o  m
    try {
      Thread.currentThread().sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    t.interrupt();
  }

  public static void run() {
    int counter = 0;
    while (!Thread.interrupted()) {
      counter++;
    }
    System.out.println("Counter:" + counter);
  }
}

The code above generates the following result.





Example 3

The Thread class has a non-static isInterrupted() method that can be used to test if a thread has been interrupted.

public class Main {
  public static void main(String[] args) {
    System.out.println("#1:" + Thread.interrupted());
//  ww w  .  j av a 2s. c om
    Thread mainThread = Thread.currentThread();
    mainThread.interrupt();

    System.out.println("#2:" + mainThread.isInterrupted());

    System.out.println("#3:" + mainThread.isInterrupted());

    System.out.println("#4:" + Thread.interrupted());

    System.out.println("#5:" + mainThread.isInterrupted());
  }
}

The code above generates the following result.

Example 4

You may interrupt a blocked thread.

If a thread blocked on these three methods is interrupted, an InterruptedException is thrown and the interrupted status of the thread is cleared.

The following code starts a thread that sleeps for one second and prints a message until it is interrupted.

public class Main {
  public static void main(String[] args) throws InterruptedException{
    Thread t = new Thread(Main::run);
    t.start();/*w  w w . jav a  2s.  co m*/
    Thread.sleep(5000);
    t.interrupt();
  }

  public static void run() {
    int counter = 1;
    while (true) {
      try {
        Thread.sleep(1000);
        System.out.println("Counter:" + counter++);
      } catch (InterruptedException e) {
        System.out.println("I got  interrupted!");
      }
    }
  }
}

The code above generates the following result.