Java 让进程等待

Java 让进程等待,java,Java,我使用以下代码通过命令提示符运行终端命令 String[] command = { "zsh" }; Process p = Runtime.getRuntime().exec(command); new Thread(new SyncPipe(p.getErrorStream(), b)).start(); new Thread(new SyncPip

我使用以下代码通过命令提示符运行终端命令

String[] command =
        {
      "zsh"
          };
                Process p = Runtime.getRuntime().exec(command);
                new Thread(new SyncPipe(p.getErrorStream(), b)).start();
                new Thread(new SyncPipe(p.getInputStream(), b)).start();
                PrintWriter stdin = new PrintWriter(p.getOutputStream());
                stdin.println("source ./taxenv/bin/activate");
                stdin.println("python runner.py");
                stdin.close();
                int returnCode = 0;
                try {
                    returnCode = p.waitFor();

                    String path2 = b + "/logs.txt"; // I am getting b value passed in from gc.jsp
                    if(new File(path2).exists())
                    {
                        BufferedReader reader = new BufferedReader(new FileReader(path2));

                            while ((line1 = reader.readLine()) != null) 
                                {
                                    content= content + line1 +"<br>";
                                }
                            reader.close();
                            request.setAttribute("logs", content);

                            RequestDispatcher rd = request.getRequestDispatcher("gc.jsp");
                            rd.forward(request, response);


                }
                }
                catch (InterruptedException e) {
                    e.printStackTrace();

                }
                    System.out.println("Return code = " + returnCode +b);
    }               
    class SyncPipe implements Runnable
    {

    public SyncPipe(InputStream istrm, String c) {
          istrm_ = istrm;
          b_ = c;
      }

    @SuppressWarnings("unused")
    public void run() {
          try
          {
              final byte[] buffer = new byte[1024];
            for(int length = 0; (length = istrm_.read(buffer)) != -1; )
              {
                   str = str + IOUtils.toString(istrm_, "UTF-8") + b_;
              }
            System.out.println(str);

            String location = b_ + "/" + "logs.txt";
            File file = new File(location);
            if(!file.exists())
            {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(str);
            bw.close();


          }

          catch (Exception e)
          {
              e.printStackTrace();
          }
      }
      private final InputStream istrm_;
      private final String b_;
还是没用

现在,我补充说

bw.close() //Closing bufferedwriter
fw.close() //Closing file writer
TimeUnit.SECONDS.sleep(5);
这适用于小文件,所以基本上问题在于代码是从行开始的

字符串path2=b+“/logs.txt”

必须等待进程p完成


如何执行此操作?

您的问题是在
SyncPipe
完成对文件的写入之前尝试读取文件。您可以通过等待所有线程完成来解决此问题(
join()

说明:由于进程
p
停止,当输入/错误流关闭时,同步管道线程将停止。然后,它会将所有内容写入文件,并相应地关闭文件。之后,线程将正确停止

join
方法告诉主线程(join的调用者)等待线程停止(join的调用者,例如threadError)
waitFor
在某种程度上等同于
join


在此之后,您可以确定所有线程都已正确停止(
p
threadError
threadInput
),因此所有文件都已写入磁盘。现在您可以阅读它们了。

异常是否阻止转发?我不知道..当我刷新页面时,我得到的输出控制台日志也是空的..我想有一些逻辑错误,我需要在完成returnCode=p.waitFor()后才处理if循环;但是我该怎么做呢?试试While(p.waitFor()==0){}
Process p = Runtime.getRuntime().exec(command);
Thread threadError = new Thread(new SyncPipe(p.getErrorStream(), b));
Thread threadInput = new Thread(new SyncPipe(p.getInputStream(), b));

threadError.start();
threadInput.start();

/* writing to process */

// wait until your process finished
p.waitFor();

// wait for both threads until they finished writing to files
threadError.join();
threadInput.join();

// read your files