gpt4 book ai didi

java - 优雅地关闭java应用程序(多线程)

转载 作者:太空宇宙 更新时间:2023-11-04 11:20:42 26 4
gpt4 key购买 nike

我正在尝试设置一个关闭 Hook 来处理 SIGTERM (kill -15)。它关闭了,但看起来并没有优雅地完成**处理**功能,因为它从未输出日志“线程已关闭”。

public class Runner {
public static void main(String[] args) {
Test test = new Test();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
logger.warn("Shutting things down..."); // This works
test.stop();
} catch (Exception ex) {
logger.error("Error shutting the app gracefully", ex);
}
}
});

test.processing();
}
}


public class Test {
private volatile boolean processingExit = false;
public void stop() {
processingExit = true;
}

public void processing() {
while (!processingExit) {
//do work here
logger.info("doing work... keep printing..."); //This works until I send a kill -15 signal
}
// This log never works
logger.info("Thread has been shutdown"); // This doesn't works
}
}

最佳答案

问题在于,一旦关闭钩子(Hook)线程完成,进程就会停止,您需要让关闭钩子(Hook)线程等待主线程。

复制自 https://stackoverflow.com/a/2922031/1544715

来自the docs :

When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt.

关于java - 优雅地关闭java应用程序(多线程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44936802/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com