gpt4 book ai didi

java - 终止运行 jar 的线程

转载 作者:行者123 更新时间:2023-11-29 06:17:39 25 4
gpt4 key购买 nike

我有一个扩展 Thread 的类,当启动时,它运行一个 jar 的 Main 方法。当我终止线程时,它不会终止它启动的进程。我该怎么做?谢谢!

下面是来 self 的自定义 Thread 类的 run() 方法。

@Override
public void run() {
if(parent != null) {
MessageConsole console = new MessageConsole(parent.getConsole().getTextPane());
console.redirectOut(new Color(240, 240, 240), null);
console.redirectErr(Color.RED, null);
console.setMessageLines(20);
}
if(oParent != null) {
MessageConsole console = new MessageConsole(oParent.getConsole().getTextPane());
console.redirectOut(new Color(240, 240, 240), null);
console.redirectErr(Color.RED, null);
console.setMessageLines(20);
}
try {
somejar.SomeJar.main(args);
} catch (Exception ex) {
System.err.println("Engine failed to start!\nSuggestion: Restart the application, and if the issue is not fixed reinstall the application.");
}
}

最佳答案

When I terminate the Thread it does not kill the process it started. How do I go about that?

没有可靠的方法可以做到这一点。

首先,没有可靠的方法来终止线程。 try 的首选方法是在线程上调用 Thread.interrupt(),但这可能会被忽略。如果您调用已弃用方法Thread.stop(),您可能会破坏 JVM 的稳定性。

其次,即使假设您终止了 JAR 线程,您也无法可靠地终止它创建的任何子线程。您无法可靠地将子线程与应用程序其他部分创建的其他线程区分开来。而且,即使您可以识别它们,也无法可靠地杀死它们。

您能做的最好的事情就是启动一个新的 JVM 作为外部进程来运行 JAR。在正常情况下,JVM 可以可靠地终止它创建的外部进程。 (也有异常(exception),例如 setuid 命令,但它们在这里不应该成为问题。)

关于java - 终止运行 jar 的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4465808/

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