Home  >  Article  >  Java  >  How to end a thread in java

How to end a thread in java

王林
王林Original
2020-05-16 17:12:212714browse

How to end a thread in java

We can use the interrupt() method to end the thread

This method is divided into two situations:

(1) The thread is in a blocked state, If the sleep method is used.

(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, while in the second case the thread will exit directly.

(Recommended video tutorial: java video)

Specific code:

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("线程已经退出!"); 
    } }

Output result:

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

sleep interrupted
线程已经退出!

Recommended tutorial:JavaDevelopmentIntroduction

The above is the detailed content of How to end a thread in java. For more information, please follow other related articles on the PHP Chinese website!

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