Java: How to make this main thread wait for the new thread to terminate

后端 未结 3 2005
挽巷
挽巷 2021-02-10 21:37

I have a java class that creates a process, called child, using ProcessBuilder. The child process generates a lot of output that I am draining on a separate thread to keep the

相关标签:
3条回答
  • 2021-02-10 22:25

    You can join on that thread. You would get the instance of the thread and when needed to wait invoke 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 suggest a CountdownLatch, CyclicBarrier or even a Future but I find this to be easiest to implement on a very low level.

    0 讨论(0)
  • 2021-02-10 22:25
    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();
    
    0 讨论(0)
  • 2021-02-10 22:34

    You have to assign your thread to a variable and later call join() on this variable.

    0 讨论(0)
提交回复
热议问题