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

How to stop a thread in java

(*-*)浩
(*-*)浩Original
2019-05-28 10:14:266897browse

How to stop Java threads has always been a common problem when developing multi-threaded programs. Many people have asked me, so I will summarize it here today in the hope that more people will know how to safely end a running thread in Java.

How to stop a thread in java

In Java multi-threaded programming, the java.lang.Thread type contains a series of methods start(), stop(), stop(Throwable) and suspend( ), destroy() and resume(). Through these methods, we can perform convenient operations on threads, but among these methods, only the start() method is retained.

The reasons for abandoning these methods are explained in the JDK help documentation and an article from Sun "Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?"

So, how should we stop the thread?

Use shared variables
In this method, the reason why shared variables are introduced is because the variables can be used by multiple threads performing the same task. As a signal whether to interrupt, notify the execution of the interrupted thread.

public class ThreadFlag extends Thread 
{ 
    public volatile boolean exit = false; 
 
    public void run() 
    { 
        while (!exit); 
    } 
    public static void main(String[] args) throws Exception 
    { 
        ThreadFlag thread = new ThreadFlag(); 
        thread.start(); 
        sleep(3000); // 主线程延迟3秒 
        thread.exit = true;  // 终止线程thread 
        thread.join(); 
        System.out.println("线程退出!"); 
    } 
}

In the above code, an exit flag exit is defined. When exit is true, the while loop exits, and the default value of exit is false. When defining exit, a Java keyword volatile is used. The purpose of this keyword is to synchronize exit, which means that only one thread can modify the value of exit at the same time.

The above is the detailed content of How to stop 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