Process 类型对象的 waitFor() 方法的时候当前线程会被阻塞掉,因为InputStream in = Process.getInputStream();或 InputStream err = Process.getErrorStream(); 这2个流中的一个会被阻塞住,所以解决的办法可以是用多线程来解决,可以参看http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps_p.html 。
但还有另一种方法可以尝试,
Java代码
String[] cmds = {...};//command and arg ProcessBuilder builder = new ProcessBuilder(cmds); //both read inputstream and errstream builder.redirectErrorStream(true); Process process = builder.start(); BufferedReader br = new BufferedReader(new InputStreamReader(process .getInputStream())); String readLine = br.readLine(); while (readLine != null) { System.out.println(readLine); readLine = br.readLine(); } int resultValue = process.waitFor(); String[] cmds = {...};//command and arg ProcessBuilder builder = new ProcessBuilder(cmds); //both read inputstream and errstream builder.redirectErrorStream(true); Process process = builder.start(); BufferedReader br = new BufferedReader(new InputStreamReader(process .getInputStream())); String readLine = br.readLine(); while (readLine != null) { System.out.println(readLine); readLine = br.readLine(); } int resultValue = process.waitFor();
builder.redirectErrorStream(true); 和BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); 这样使用就可以在一个线程中执行,而保证不被阻塞住。