Java Thread interrupt() Method
Example
Interrupt a thread while it sleeps:
public class Main {
static class MyThread extends Thread {
public void run() {
try {
Thread.sleep(5000);
System.out.println("The thread woke up");
} catch (InterruptedException e) {
System.out.println("The thread was interrupted");
}
}
}
public static void main(String[] args) throws InterruptedException {
MyThread thread = new MyThread();
thread.start();
thread.interrupt();
thread.join();
}
}
Definition and Usage
The interrupt() method sends an interrupt signal to a thread. It is a way to ask the thread to stop what it is doing.
If the thread is waiting in sleep() or join(), it stops waiting and gets an InterruptedException. If not, the interrupted status of the thread (a flag that is true or false) is set to true.
Tip: Use the isInterrupted() method to check if a thread has been interrupted.
Syntax
public void interrupt()
Parameter Values
None.
Related Pages
❮ Thread Methods