简体   繁体   English

如何停止另一个Java线程?

[英]How can I stop a Java Thread from another one?

Maybe I'm thinking to complicated, but I have the following situation: 也许我在想复杂化,但是我有以下情况:

I have a class Server.java extending Thread with the following relevant part of the code: 我有一个Server.java类,它使用以下代码的相关部分扩展了Thread:

public void run() {
    while(listening) {
        try {
            ServerThread cst = new ServerThread(serverSocket.accept());
            cst.start();
        } catch (IOException e) {
            listening = false;
            System.out.println(e.getMessage());
        }
    }
}

My ServerThread then handles all the incoming stuff. 然后,我的ServerThread处理所有传入的内容。

My question now is, if there is any possibility to stop this Thread (Server) like for example over the command line. 我现在的问题是,是否有可能像通过命令行那样停止此线程(服务器)。

I tried to add a new class, that would handle command line input and .interrupt() this Thread, but that kinda just made a big mess.. 我试图添加一个新类,该类可以处理命令行输入和该线程的.interrupt(),但那有点麻烦。

Here's one way: 这是一种方法:

  1. Provide a setter for listening that can be accessed from another class/thread. 提供一个listening ,可以从另一个类/线程访问。

  2. Set a reasonable timeout (say, 1 sec) on the ServerSocket and handle the SocketTimeoutException . ServerSocket上设置一个合理的超时时间(例如1秒),并处理SocketTimeoutException

To stop the thread, set listening to false and within 1 second the thread will stop. 要停止线程,请将listening设置为false ,则线程将在1秒钟内停止。 If you want finer control, investigate the async I/O classes in java.nio . 如果需要更好的控制,请研究java.nio的异步I / O类。

您可以使用setter将侦听定义为volatile ,并在每次要停止Thread时将其设置为false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM