Thread Interruption Mechanisms in Java
Natural Termination
A thread terminates naturally when its run method completes execution or when an unhandled exception causes premature termination.
Deprecated API Methods
The following methods have been deprecated and are not recommended for use:
suspend(): Suspends a threadresume(): Resumes a suspended threadstop(): Stops a thread abruptly
These method are discouraged due to serious side effects. For instance, when suspend() is invoked, the thread retains all acquired resources (such as locks) while entering a suspanded state, which can lead to deadlock situations.
Similarly, the stop() method does not ensure proper resource cleanup when terminating a thread. It denies the thread the opportunity to release resources gracefully, potentially leaving the appplication in an inconsistent state.
Due to these adverse effects, the suspend(), resume(), and stop() methods have been marked as deprecated.
Cooperative Interruption
interrupt()
Signals a thread to interrupt itself cooperatively:
public static void main(String[] args) throws ExecutionException, InterruptedException, IOException {
WorkerThread worker = new Thread(() -> {
Thread current = Thread.currentThread();
while (!current.isInterrupted()) {
// Perform work here
}
System.out.println(current.getName() + " received interruption signal");
});
worker.start();
System.out.println("Press any key to trigger interruption");
System.in.read();
worker.interrupt();
}
isInterrupted()
Checks whether a thread has been interrupted:
public static void main(String[] args) throws ExecutionException, InterruptedException, IOException {
WorkerThread worker = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
// Continue processing
}
System.out.println("Interruption detected");
});
worker.start();
System.out.println("Press any key to interrupt the thread");
System.in.read();
worker.interrupt();
}
Thread.interrupted()
Tests whether the current thread has been interrupted and clears the interrupt status if it was set, returning the thread to a normal state:
public static void main(String[] args) throws ExecutionException, InterruptedException, IOException {
WorkerThread worker = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
// Process until interrupted
}
System.out.println("First check: " + Thread.interrupted());
System.out.println("Second check: " + Thread.interrupted());
});
worker.start();
System.out.println("Press any key to examine thread status");
System.in.read();
worker.interrupt();
}