Java:如何使此主线程等待新线程终止 [英] Java: How to make this main thread wait for the new thread to terminate

查看:257
本文介绍了Java:如何使此主线程等待新线程终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java类,可以使用ProcessBuilder创建一个称为子进程的进程.子进程会产生大量输出,我正在消耗一个单独的线程,以防止主线程被阻塞.但是,稍后,我需要等待输出线程完成/终止,然后再继续操作,我不确定该怎么做.我认为join()是执行此操作的常用方法,但是我不确定在这种情况下如何执行此操作.这是Java代码的相关部分.

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 main thread from getting blocked. However, a little later on I need to wait for the output thread to complete/terminate before going on, and I'm not sure how to do that. I think that join() is the usual way to do this but I'm not sure how to do that in this case. Here is the relevant part of the java code.

    // 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方法时得到它.

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

其他人会建议使用CountdownLatch,CyclicBarrier甚至是Future,但是我发现这是最简单的实现,而且级别很低.

Others will suggest a CountdownLatch, CyclicBarrier or even a Future but I find this to be easiest to implement on a very low level.

这篇关于Java:如何使此主线程等待新线程终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆