以 Runtime.getRuntime().exec() 开头的 jar 运行时间比从命令行运行的时间长

A jar started with Runtime.getRuntime().exec() runs longer than from command line

我有以下问题:

我有一个简单的 .jar 程序,它在文本控制台中写入..

如果我开始使用 cmd (java -jar myProgram.jar) 程序 运行s 1 second.

但我想使用 JButton 从另一个程序启动程序:

startMyProgram.addActionListener(new ActionListener() {
        @Override
             public void actionPerformed(ActionEvent e) {
             // Run a java app in a separate system process
             Process proc = Runtime.getRuntime().exec("java -jar myProgram.jar");

             // Then retreive the process output
             InputStream in = proc.getInputStream();
             InputStream err = proc.getErrorStream();
             System.out.println(convertStreamToString(in));
        }
 });

如果我使用第二种方式(JButton 方式),程序 运行s 10 second.

为什么?为什么运行这么久? 如果我开始让他通过另一个线程,需要 10 秒的时间。

基于 When Runtime Exec Won't 的 StreamGobbler,没有直接扩展 Thread。

public class StreamGobbler implements Runnable {
    private InputStream in;
    public StreamGobbler(InputStream in) {
        this.in = in;
    }
    @Override
    public void run() {
        InputStreamReader isr = new InputStreamReader(in);
        BufferedReader br = new BufferedReader(isr);
        try {
            String line = null;
            while ((line = br.readLine()) != null) {
                // could log it here
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在 exec()

之后使用它来接收流中的所有输出
Process proc = Runtime.getRuntime().exec("java -jar myProgram.jar");
...
new Thread(new StreamGobbler(in)).start();
new Thread(new StreamGobbler(err)).start();;