线程在终止之前不会输出流

时间:2019-06-27 19:06:31

标签: java multithreading

我试图通过运行外部jar来打印实时输出,它在线程中运行并且jar确实得到执行,问题是直到线程终止后,输出才打印出来。

public void run() {
    Process proc = null;
    try {

        proc = Runtime.getRuntime().exec("java -jar A.jar");    
        InputStream in = proc.getInputStream();
        InputStream err = proc.getErrorStream();

        BufferedInputStream bis = new BufferedInputStream(in);
        BufferedInputStream bes = new BufferedInputStream(err);

        String iss = IOUtils.toString(in, "UTF8");
        String ess = IOUtils.toString(err, "UTF8");

        System.out.println(iss);
        System.out.println(ess);

    } catch (IOException e) {
        e.printStackTrace();
        this.interrupt();
    }
}

1 个答案:

答案 0 :(得分:0)

您需要在单独的线程中同时运行它们,以便同时读取它们。

public void run() {
    try {
        Process proc = Runtime.getRuntime().exec("/home/martin/test.py");
        InputStream in = proc.getInputStream();
        InputStream err = proc.getErrorStream();

        Thread tIn = new Thread(() -> {
            try {
                while (true) {
                    int ch;
                    ch = in.read();
                    if (ch < 0)
                        break;
                    System.out.print((char) ch);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        Thread tErr = new Thread(() -> {
            try {
                while (true) {
                    int ch;
                    ch = err.read();
                    if (ch < 0)
                        break;
                    System.err.print((char) ch);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        tIn.start();
        tErr.start();

        try {
            tIn.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            tErr.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // this.interrupt();
    } catch (IOException e) {
        e.printStackTrace();
        // this.interrupt();
    }
}

这是单个函数中的快捷方式。当然,最好编写一个包装该功能的类。