fth*_*ker 4 java multithreading process interrupted-exception
我刚刚通过exec()调用创建了一个进程,现在我正在使用它的.waitFor()方法.我需要捕获一个InterruptedException,但我不确定我应该在catch代码块中放置什么.我想收到退出代码,但如果当前线程被中断,我不会.如果线程被中断,我该怎么办才能让退出代码退出进程?
例:
import java.io.IOException;
public class Exectest {
public static void main(String args[]){
int exitval;
try {
Process p = Runtime.getRuntime().exec("ls -la ~/");
exitval = p.waitFor();
System.out.println(exitval);
} catch (IOException e) {
//Call failed, notify user.
} catch (InterruptedException e) {
//waitFor() didn't complete. I still want to get the exit val.
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果我是你,我会把它放到catch块中:
p.destroy();
exitval = p.exitValue();
Run Code Online (Sandbox Code Playgroud)
由于您的线程已被中断,因此出现了问题.destroy()将强制终止进程,然后exitValue()将为您提供退出值(应该是一个错误代码,因为它已被终止).
更多http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Process.html