Java ProcessBuilder在线程中不起作用

时间:2019-07-25 08:50:45

标签: java processbuilder java-threads

我正在使用Java ProcessBuilder执行两个Shell脚本。我希望两次执行之间有10秒的时间间隔。这就是为什么我使用线程。但是下面的代码不能执行shell脚本(没有线程就可以执行)。

public void execute() {

    new Thread(new Runnable() {
        public void run() {
            Process process_1;
            try {

                List<String> cmdList_1 = new ArrayList<String>();

                cmdList_1.add("sh");
                cmdList_1.add("command_1.sh");
                ProcessBuilder pb = new ProcessBuilder(cmdList_1);
                process_1 = pb.start();
                process_1.waitFor();

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }).start();

    new Thread(new Runnable() {
        public void run() {
            Process process_2;
            try {
                Thread.sleep(10000);

                List<String> cmdList_2 = new ArrayList<String>();

                cmdList_2.add("sh");
                cmdList_2.add("command_2.sh");
                ProcessBuilder pb = new ProcessBuilder(cmdList_2);
                process_2 = pb.start();
                process_2.waitFor();

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }).start();
}  

如何修复我的代码?还是有更好的方法来实现我的抱负?

预先感谢

1 个答案:

答案 0 :(得分:0)

尝试使用该过程的输出,如下所示:

ProcessBuilder processBuilder = new ProcessBuilder();
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader((new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
    System.out.println(line);
}