【发布时间】: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