2010-05-07 182 views
4

我有一个java类,它使用ProcessBuilder创建一个名为child的进程。子进程生成大量的输出,我在一个单独的线程上排空以防止主线程被阻塞。然而,稍后我需要等待输出线程完成/终止之前,我不知道如何做到这一点。我认为join()是通常的做法,但我不确定在这种情况下如何做到这一点。这里是java代码的相关部分。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(); 

回答

15

您可以加入该线程。您将获得线程的实例,并在需要时等待调用其联接方法。

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

其他人会提出的CountDownLatch,的CyclicBarrier甚至是未来,但我觉得这是最容易在一个非常低的水平来实现。

3

你有你的线程分配给一个变量,过一会儿给join()此变量。

3
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();