gpt4 book ai didi

java - Java 中没有尽头的线程

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:40:43 25 4
gpt4 key购买 nike

我有一个用 Java 编写的程序,它使用 3 个线程。在 IDE (Netbeans) 中一切正常,当我杀死它时,它会破坏所有线程。当我从命令行启动它并按 Ctrl-C 时,线程会继续运行。处理此问题的最佳方法是什么?

它是否会杀死主线程,因为我想在那之后我可以使用标志?

最佳答案

您可以在您的主线程上注册一个关闭 Hook ,以优雅地清理其他线程。

public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
System.out.println("System shutting down");
// tell your other threads to shut down from here
// the best way to do this is to set a flag
// that they will pick up on and exit gracefully
}
});
}

关于java - Java 中没有尽头的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11721036/

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