Home >Java >javaTutorial >Java Example - Terminate Thread

Java Example - Terminate Thread

黄舟
黄舟Original
2016-12-27 13:38:151291browse

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

This article introduces you to using the interrupt method to interrupt a thread.

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

(1) The thread is in a blocked state, such as using the sleep method.

(2) Use while(!isInterrupted()){...} to determine whether the thread is interrupted.

In the first case using the interrupt method, the sleep method will throw an InterruptedException exception, while in the second case the thread will exit directly. The following code demonstrates the use of the 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 output result of the above code is:

在50秒之内按任意键中断线程!
sleep interrupted
线程已经退出!

The above is the content of the Java instance - terminating the thread. For more information, please Follow the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn