一千萬個為什麽

搜索

Java:如何使這個主線程等待新線程終止


我有一個java類,使用ProcessBuilder創建一個名為child的進程。子進程生成大量輸出,我在一個單獨的線程上耗盡,以防止主線程被阻塞。但是,稍後我需要等待輸出線程完成/終止才能繼續,我不知道該怎麽做。我認為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();

最佳答案

您可以加入該主題。您將獲得該線程的實例,並在需要時等待調用其join方法。

 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甚至是Future,但我發現這是最容易在非常低的水平上實現的。

轉載註明原文: Java:如何使這個主線程等待新線程終止

猜你喜歡