In Java, interrupting a thread is a mechanism that allows one thread to signal another thread to interrupt its current task and possibly terminate. When a thread is interrupted, it receives an InterruptedException and can decide how to handle it, either by throwing the exception, ignoring it, or handling it in some other way.
To interrupt a thread in Java, you can call the interrupt() method on the thread object. This sets a flag on the thread that indicates it has been interrupted. The interrupted thread can then periodically check for the flag and decide how to handle the interruption.
Here's an example that demonstrates how to interrupt a thread in Java:
public class InterruptExample {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Working...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted while sleeping");
Thread.currentThread().interrupt();
}
}
System.out.println("Interrupted while working");
});
thread.start();
Thread.sleep(5000);
thread.interrupt();
}
}
In this example, we create a new thread that runs a loop that prints "Working..." every second. The loop checks if the thread has been interrupted by calling Thread.currentThread().isInterrupted(). If the flag is set, the loop ends, and the thread prints "Interrupted while working". If the thread is interrupted while sleeping, it catches the InterruptedException, sets the interrupt flag, and prints "Interrupted while sleeping".
In the main() method, we start the thread and wait for 5 seconds before interrupting it by calling thread.interrupt(). When the thread receives the interrupt signal, it sets the flag, and the loop ends, and the thread terminates.
It's important to note that interrupting a thread does not guarantee that it will immediately stop running. The thread may continue running until it reaches a safe stopping point, such as the end of a loop or a synchronization block. Therefore, it's important to design the thread's code to handle interruptions gracefully and ensure that it can terminate safely.