繁体   English   中英

终止运行jar的线程

[英]Terminate a Thread thats running a jar

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

下面是我自定义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.");
        }
    }

当我终止线程时,它不会终止其启动的进程。 我该怎么办?

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

首先,没有可靠的方法来终止线程。 尝试的首选方法是在Thread.interrupt()上调用Thread.interrupt() ,但这可能会被忽略。 如果调用不推荐使用的方法Thread.stop() ,则可能会使JVM不稳定。

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

最好的办法是启动一个新的JVM,作为运行JAR的外部进程。 在正常情况下,JVM可以可靠地终止其创建的外部进程。 (有一些例外,例如setuid命令,但在这里不应该成为问题。)

您必须终止进程才能终止线程。

您可以用信号通知它停止,例如中断()或引发异常,但是使其停止的唯一方法是使其从run()方法返回或引发Throwable。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM