我有一个Java类,使用ProcessBuilder创建了一个名为child的进程。子进程生成大量输出,我正在另一个线程中进行处理以避免主线程被阻塞。但是稍后我需要等待输出线程完成/终止才能继续执行,我不确定如何做到这一点。我认为join()是通常的方法,但我不确定在这种情况下该如何使用。以下是Java代码的相关部分。
// Capture output from process called child on a separate thread
final StringBuffer outtext = new StringBuffer("");
new Thread(new Runnable() {
public void run() {
InputStream in = null;
in = child.getInputStream();
try {
if (in != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = reader.readLine();
while ((line != null)) {
outtext.append(line).append("\n");
ServerFile.appendUserOpTextFile(userName, opname, outfile, line+"\n");
line = reader.readLine();
}
}
} catch (IOException iox) {
throw new RuntimeException(iox);
}
}
}).start();
// Write input to for the child process on this main thread
//
String intext = ServerFile.readUserOpTextFile(userName, opname, infile);
OutputStream out = child.getOutputStream();
try {
out.write(intext.getBytes());
out.close();
} catch (IOException iox) {
throw new RuntimeException(iox);
}
// ***HERE IS WHERE I NEED TO WAIT FOR THE THREAD TO FINISH ***
// Other code goes here that needs to wait for outtext to get all
// of the output from the process
// Then, finally, when all the remaining code is finished, I return
// the contents of outtext
return outtext.toString();