Home > Java > javaTutorial > How to end a java thread

How to end a java thread

WBOY
Release: 2023-05-14 17:07:06
forward
1448 people have browsed it

1. The run() method to complete thread running.

2. The thread throws an uncaught Exception or Error.

3. Another thread calls the stop() method of this thread (this method has been abandoned). They still exist, but you shouldn't use them in new code and try to eliminate them in existing code.

Example

public class ServerThread extends Thread {
    //volatile修饰符用来保证其它线程读取的总是该变量的最新的值
    public volatile boolean exit = false;
 
    @Override
    public void run() {
        ServerSocket serverSocket = new ServerSocket(8080);
        while(!exit){
            serverSocket.accept(); //阻塞等待客户端消息
            ...
        }
    }
 
    public static void main(String[] args) {
        ServerThread t = new ServerThread();
        t.start();
        ...
        t.exit = true; //修改标志位,退出线程
    }
}
Copy after login

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

Related labels:
source:yisu.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template