Thread Interrupt In Java Example
Chapter:
Thread
Last Updated:
06-07-2016 11:20:20 UTC
Program:
/* ............... START ............... */
public class JavaThreadInterrupt {
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());
}
}
/* ............... END ............... */
Output
Notes:
-
If any thread is in sleeping or waiting state if we call the interrupt() method on the thread it throws InterruptedException and breaks all Operations.
- A thread sends an interrupt by invoking interrupt on the Thread object for the thread to be interrupted.
- Three methods provided by the Thread class for interrupting a thread are below.
- 1. public void interrupt().
- 2. public static boolean interrupted().
- 3. public boolean isInterrupted().
Tags
Thread Interrupt, Java