java.lang.Process 阻塞问题


关键字: java

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代码
  1. String[] cmds = {...};//command and arg  
  2. ProcessBuilder builder = new ProcessBuilder(cmds);  
  3. //both read inputstream and errstream  
  4. builder.redirectErrorStream(true);  
  5. Process process = builder.start();  
  6. BufferedReader br = new BufferedReader(new InputStreamReader(process  
  7.     .getInputStream()));  
  8. String readLine = br.readLine();  
  9. while (readLine != null) {  
  10.    System.out.println(readLine);  
  11.    readLine = br.readLine();  
  12. }  
  13. 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())); 这样使用就可以在一个线程中执行,而保证不被阻塞住。

 

你可能感兴趣的:(process)