java调用shell process has not exited

*

http://kingj.iteye.com/blog/1420586

,出现了

java.lang.IllegalThreadStateException: process has not exited

at java.lang.Win32Process.exitValue(Native Method)

异常,后台一百度发现,jdk实现process时,调用外部命令不是同步的调用,而是异步执行。所以tree命令还没有执行成功就返回,jdk抛出异常。

int status=process.exitValue();

我的解决方法是在这句前面使用Thread.sleep(1000);

或者

原因是exitValue()方法并不会等待外部进程结束。如果外部进程还未结束,exitValue()将会抛出IllegalThreadStateException。解决办法就是调用Process的waitfor()方法。waitfor()方法会挂起当前线程,一直等到外部进程结束。当然使用exitValue()或者waitfor()完全取决你的需求。可以设个boolean标志,来确定使用哪个。运行下面的代码:

*