Java: How to make this main thread wait for the completion of a new thread

I have a java class that creates a process called a child using ProcessBuilder. The child process generates a lot of output, which I drain in a separate thread so that the main thread does not block. However, a bit later I need to wait for the output stream to finish or complete before continuing, and I don't know how to do it. I think join () is the usual way to do this, but I'm not sure how to do this in this case. Here is the relevant piece of java code.

// 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(); 
+4
source share
3 answers

You can join this thread. You will get a stream instance and, if necessary, to animate its join method.

  Thread th = new Thread(new Runnable() { ... } ); th.start(); //do work //when need to wait for it to finish th.join(); //th has now finished 

Others will offer CountdownLatch, CyclicBarrier or even the future, but I find it easiest to implement at a very low level.

+15
source

You must assign your stream to a variable and later call join() on that variable.

+3
source
 final StringBuffer outtext = new StringBuffer(""); Thread outputDrainThread = new Thread(new Runnable() { public void run() { // ... } }).start(); // ... // ***HERE IS WHERE I NEED TO WAIT FOR THE THREAD TO FINISH *** outputDrainThread.join(); // ... return outtext.toString(); 
+3
source

Source: https://habr.com/ru/post/1309134/


All Articles