ProcessBuilder를 사용하여 child라는 프로세스를 만드는 Java 클래스가 있습니다. 하위 프로세스는 메인 스레드가 차단되는 것을 막기 위해 별도의 스레드에서 많은 양의 출력을 생성합니다. 그러나 조금 후에 출력 스레드가 완료/종료되기를 기다려야 할 필요가 있습니다. 어떻게해야할지 모르겠습니다. 나는 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();