【问题标题】:thread pool server shut down gracefully线程池服务器正常关闭
【发布时间】:2015-10-21 11:54:06
【问题描述】:

我有一个使用线程池实现的简单 http 服务器。我想优雅地关闭服务器。我提到了帖子Best Way to Gracefully Shutdown a Java Command Line Program 这是基本代码:

 public static void main(String[] args) {
    ThreadPoolServer threadserver = new ThreadPoolServer(9000);
    new Thread(threadserver).start();
    threadserver.attachShutDownHook();
    while (true) {
        try {
            Thread.sleep(20 * 10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public synchronized void stopthread(){
    this.shutdown = true;
    try {
        this.serverSocket.close();
    } catch (IOException e) {
        throw new RuntimeException("Error closing server", e);
    }
}

public synchronized void attachShutDownHook() {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            stopthread();
        }
    });
}

但它似乎并没有停止正确的方式,有什么想法吗?谢谢。

【问题讨论】:

  • 它不停止正确的方式是什么意思?你能解释一下你遇到的问题吗?

标签: java multithreading shutdown httpserver


【解决方案1】:

这段代码太小了。

但乍一看,我没有在主 while 循环中看到任何对关闭值的检查。其次,应该在之后设置变量,并且可能加入监听线程是值得的。在 run 方法中,我假设您正确处理了异步关闭引发的异常。

【讨论】:

    猜你喜欢
    • 2010-11-29
    • 2023-03-02
    • 1970-01-01
    • 2013-11-15
    • 2013-02-27
    • 2011-07-14
    • 2018-09-03
    • 2014-05-05
    • 2011-04-28
    相关资源
    最近更新 更多