Process.waitFor() a thread

£可爱£侵袭症+ 提交于 2019-12-06 13:04:08

You can use Thread.join(...) to wait for a Thread to finish. Note that the call throws InterruptedException if the current thread receives an interrupt before the thread you are waiting for finishes.

Here's general code for doing what you want to do. In this case there is both input and output: I am piping someFile into the process and piping the output to System.out. Files.copy() and ByteStreams.copy() are just Guava convenience methods to hook up an InputStream to an OutputStream. We then wait for the command to finish.

final Process pr = Runtime.getRuntime().exec(cmd);

new Thread() {
    public void run() {
        try (OutputStream stdin = pr.getOutputStream()) {
            Files.copy(someFile, stdin);
        } 
        catch (IOException e) { e.printStackTrace(); }
    }
}.start();

new Thread() {
    public void run() {
        try (InputStream stdout = pr.getInputStream()) {
            ByteStreams.copy(stdout, System.out);
        } 
        catch (IOException e) { e.printStackTrace(); }  
    }
}.start();              

int exitVal = pr.waitFor();
if( exitVal == 0 )
    System.out.println("Command succeeded!");
else    
    System.out.println("Exited with error code " + exitVal);

A more verbose version if you are running prior to Java 7 with the try-with-resources block:

final Process pr = Runtime.getRuntime().exec(cmd);

new Thread() {
    public void run() {
        OutputStream stdin = null;
        try {
            Files.copy(someFile, stdin = pr.getOutputStream());
        } 
        catch (IOException e) { e.printStackTrace(); }
        finally {
            if( stdin != null ) {
                try { stdin.close(); } 
                catch (IOException e) { e.printStackTrace(); }
            }
        }               
    }
}.start();

new Thread() {
    public void run() {
        InputStream stdout = null;
        try {
            ByteStreams.copy(stdout = pr.getInputStream(), System.out);
        } 
        catch (IOException e) { e.printStackTrace(); }
        finally {
            if( stdout != null ) {
                try { stdout.close(); } 
                catch (IOException e) { e.printStackTrace(); }
            }
        }               
    }
}.start();              

int exitVal = pr.waitFor();
if( exitVal == 0 )
    System.out.println("Command succeeded!");
else    
    System.out.println("Exited with error code " + exitVal);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!