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

How to end a java thread

WBOY
WBOYforward
2023-05-14 17:07:061432browse

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; //修改标志位,退出线程
    }
}

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete