Java:如何让这个主线程等待新线程终止

标签 java multithreading

我有一个 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();

最佳答案

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

 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:如何让这个主线程等待新线程终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2790196/

相关文章:

java - 线程 "main"org.eclipse.swt.SWTError : XPCOM error 0x80004005 in swt. mozilla 中出现异常

java - 重写父类(super class)非抽象方法。访问父类(super class)中的私有(private)属性(?)

c++ - 'std::thread' 的初始化没有匹配的构造函数

c# - Winforms:从另一个类更新表单上的标签

iphone - 如何更新 UI 以显示 Core Data 长时间运行的进程?

java - String.equalsIgnoreCase 仅对第一个 switch case 返回 true

java - 跟踪多个数组列表

java - 扩展 DOM 元素功能的正确方法是什么?

java - 协调两个线程时的并发问题

java - 当指定多个条件锁定时会出现死锁