Java - Thread Thread Interruption

Introduction

You can interrupt a thread by using the interrupt() method.

It is just a hint.

A thread could be in one of the two states when it is interrupted: running or blocked.

If a thread is interrupted when it is running, its interrupted status is set by the JVM.

You can check its interrupted status by calling the Thread.interrupted() static method.

If you call Thread.interrupted() method again on the same thread and if the first call returned true, the subsequent calls will return false, unless the thread is interrupted after the first call but before the subsequent calls.

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

Demo

class Main {
  public static void main(String[] args) {
    System.out.println("#1:" + Thread.interrupted());

    // 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());
  }//from  w w w  .  j a va  2 s .c  o m
}

Result

Related Topics