Latest web development tutorials

Java Examples - terminate the thread

Java Examples Java Examples

Java Thread originally provided in the stop () method to terminate the thread, but this method is not secure, it is generally not recommended.

In this paper, we show the use of interrupt method interrupt thread.

Using the interrupt method to end the thread can be divided into two situations:

  • (1) thread is blocked, such as the use of sleep method.
  • (2) use while (! IsInterrupted ()) {......} to determine whether the thread is interrupted.

In the first case using the interrupt method, sleep method throws an InterruptedException exception, while in the second case the thread will exit. The following code demonstrates the use of interrupt method in the first case.

/*
 author by w3cschool.cc
 ThreadInterrupt.java
 */

public class ThreadInterrupt extends Thread 
{ 
    public void run() 
    { 
        try 
        { 
            sleep(50000);  // 延迟50秒 
        } 
        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("在50秒之内按任意键中断线程!"); 
        System.in.read(); 
        thread.interrupt(); 
        thread.join(); 
        System.out.println("线程已经退出!"); 
    } 
} 

The above code is run output is:

在50秒之内按任意键中断线程!

sleep interrupted
线程已经退出!

Java Examples Java Examples