Java Examples - Terminating a Thread
Originally, Java provided the stop() method in Thread to terminate threads, but this method is unsafe, so it is generally not recommended.
This article introduces using the interrupt method to interrupt threads.
Using the interrupt method to interrupt a thread can be divided into two cases:
- (1) The thread is in a blocked state, such as when the sleep method is used.
- (2) Use while (!isInterrupted()) { ... } to determine whether the thread has been interrupted.
In the first case, using the interrupt method will cause the sleep method to throw an InterruptedException exception, while in the second case the thread will exit directly. The following code demonstrates using the interrupt method in the first case.
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 within 50 seconds to interrupt the thread!");
System.in.read();
thread.interrupt();
thread.join();
System.out.println("Thread has exited!");
}
}
The output of the above code is:
在50秒之内按任意键中断线程! sleep interrupted 线程已经退出!Other Extensions
Java Examples