Java Data Type Tutorial - Java Thread.interrupted()








Syntax

Thread.interrupted() has the following syntax.

public static boolean interrupted()

Example

In the following code shows how to use Thread.interrupted() method.

//from  w w  w  .  j av a  2 s.c o m
class ThreadDemo implements Runnable {
  public void run() {
    try {
      while (true) {
        Thread.sleep(1000);
      }
    } catch (InterruptedException e) {
      System.out.println(e.toString());
    }
  }
}

public class Main {

  public static void main(String args[]) {
    Thread t = new Thread(new ThreadDemo());
    System.out.println("Executing " + t.getName());
    // this will call run() fucntion
    t.start();

    // interrupt the threads
    if (!t.interrupted()) {
      t.interrupt();
    }
    // block until other threads finish
    try {
      t.join();
    } catch (InterruptedException e) {
    }
  }

}

The code above generates the following result.