2010-04-01 92 views
3

我有下面的代码:如何同步Java代码

Process p = Runtime.getRuntime().exec(args); 

,我想我的程序等待调用Runtime.getRuntime()EXEC(参数);完成导致它持续2-3秒,然后继续。

想法?

回答

2

这里是一个示例代码:

Process proc = Runtime.getRuntime().exec([email protected]); 
InputStream in = proc.getInputStream(); 
byte buff[] = new byte[1024]; 
int cbRead; 

try { 
    while ((cbRead = in.read(buff)) != -1) { 
     // Use the output of the process... 
    } 
} catch (IOException e) { 
    // Insert code to handle exceptions that occur 
    // when reading the process output 
} 

// No more output was available from the process, so... 

// Ensure that the process completes 
try { 
    proc.waitFor(); 
} catch (InterruptedException) { 
    // Handle exception that could occur when waiting 
    // for a spawned process to terminate 
} 

// Then examine the process exit code 
if (proc.exitValue() == 1) { 
    // Use the exit value... 
} 

你可以找到更多关于这个网站:http://docs.rinet.ru/JWP/ch14.htm

+0

是的,你是working.Thanks! 是否可以正常同步?如果我不想使用Runtime.getRuntime()。exec(args),但是 WsImport.doMain(args); – Milan 2010-04-01 09:56:34

5

使用Process.waitFor()

Process p = Runtime.getRuntime().exec(args); 
int status = p.waitFor(); 

从JavaDoc的:

导致当前线程如果需要等待,直到通过此处理对象表示的进程已经终止。如果子进程已经终止,则此方法立即返回。如果子进程尚未终止,则调用线程将被阻塞,直到子进程退出。