Java Example - Terminating Threads
In Java, the Thread class originally provided a stop() method to terminate a thread. However, this method is unsafe and is generally not recommended for use.
This tutorial introduces using the interrupt method to terminate a thread.
Using the interrupt method to terminate a thread can be divided into two scenarios:
- (1) The thread is in a blocked state, for example, by using the
sleepmethod. - (2) Using a loop like
while (!isInterrupted()) { ... }to check if the thread has been interrupted.
In the first scenario, using the interrupt method will cause the sleep method to throw an InterruptedException. In the second scenario, the thread will exit directly. The following code demonstrates the first scenario.
ThreadInterrupt.java File
public class ThreadInterrupt extends Thread {
public void run() {
try {
sleep(50000); // Delay for 50 seconds
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) throws Exception {
Thread thread = new ThreadInterrupt();
thread.start();
System.out.println("Press any key to interrupt the thread within 50 seconds!");
System.in.read();
thread.interrupt();
thread.join();
System.out.println("Thread has exited!");
}
}
The output of running the above code is:
Press any key to interrupt the thread within 50 seconds!
sleep interrupted
Thread has exited!
YouTip