2010-05-07 5 views
4

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

답변

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(); 
관련 문제