Java从run传递值

时间:2014-03-18 09:53:28

标签: java

在我的下面的程序中,如何在我的doGet()类中访问SyncPipe的str值?

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{

String[] command =
    {
  "zsh"
      };
            Process p = Runtime.getRuntime().exec(command);
            new Thread(new SyncPipe(p.getErrorStream(), response.getOutputStream())).start();
            new Thread(new SyncPipe(p.getInputStream(), response.getOutputStream())).start();
            PrintWriter stdin = new PrintWriter(p.getOutputStream());
            stdin.println("source ./taxenv/bin/activate");
            stdin.println("python runner.py");
            stdin.close();
            int returnCode = 0;
            try {
                returnCode = p.waitFor();
            }
            catch (InterruptedException e) {
                e.printStackTrace();

            } System.out.println("Return code = " + returnCode);

}               
class SyncPipe implements Runnable
{
    String str="";
public SyncPipe(InputStream istrm, OutputStream ostrm) {
      istrm_ = istrm;
      ostrm_ = ostrm;
  }
  public void run() {
      try
      {
          final byte[] buffer = new byte[1024];
          for (@SuppressWarnings("unused")
        int length = 0; (length = istrm_.read(buffer)) != -1; )
          {
             // ostrm_.write(buffer, 0, length);
              str = str + IOUtils.toString(istrm_, "UTF-8");
              //((PrintStream) ostrm_).println();
          }
          System.out.println(str);
      }
      catch (Exception e)
      {
          e.printStackTrace();
      }
  }
  @SuppressWarnings("unused")
private final OutputStream ostrm_;
  private final InputStream istrm_;
}

最后,

我想做的就是将run()的str值传递给我的doget(),我该怎么做?

2 个答案:

答案 0 :(得分:0)

您需要保留对SyncPipe的引用并使用公共getter:

SyncPipe pipe = new SyncPipe(p.getInputStream(), response.getOutputStream())
Thread thread = new Thread(pipe);
thread.start();
thread.join();
pipe.getStr();

....

class SyncPipe implements Runnable{
    String str="";
    public String getStr(){
        return str;
    }
....

答案 1 :(得分:0)

ExecutorService下运行线程,这提供了一种捕获返回值的方法  Thread执行后。

ExecutorService#submit((java.lang.Runnable, T)) - 提交Runnable任务以执行并返回表示该任务的Future。 Future的get方法将在成功完成后返回null。

代码段:

ExecutorService executor = Executors.newFixedThreadPool(2);
Future<String> future1 = executor.submit(new SyncPipe(p.getErrorStream(), response.getOutputStream()),String.class);
Future<String> future2 = executor.submit(new SyncPipe(p.getErrorStream(), response.getOutputStream()),String.class);

future1.get();// will block the execution for you and the Thread completion
future2.get();