Java Example - Terminating Threads
Originally, Java provided the stop()
method in the Thread
class to terminate threads, but this method is unsafe and is generally not recommended for use.
This article introduces the use of the interrupt
method to interrupt threads.
Using the interrupt
method to terminate threads can be categorized into two scenarios:
(1) The thread is in a blocked state, such as when using the
sleep
method.(2) Using
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 use of the interrupt
method in 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("Interrupt the thread within 50 seconds by pressing any key!");
System.in.read();
thread.interrupt();
thread.join();
System.out.println("The thread has exited!");
}
}
The output of the above code is:
Interrupt the thread within 50 seconds by pressing any key!
sleep interrupted
The thread has exited!