终止运行jar的线程

时间:2010-12-16 22:04:10

标签: java multithreading

我有一个扩展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.");
        }
    }

2 个答案:

答案 0 :(得分:3)

  

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

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

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

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

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

答案 1 :(得分:0)

如果不终止进程,则无法终止线程。

您可以发出信号停止,例如中断()或抛出异常,但让它停止的唯一方法是让它从run()方法返回或抛出一个Throwable。