上篇博文中CallMaxentThreadPoolTask類直接使用Runtime.getRuntime().exec方法調用cmd命令,結果今天在測試時發現當cmd命令執html
行出現錯誤或警告時,主控程序的waitfor方法會被阻塞一直等待下去,查了查資料發現是Runtime.getRuntime().exec方法須要本身處理java
stderr 及stdout流,而解決方法便是將它們導出用別的thread處理。socket
會形成阻塞的代碼:測試
- Process p = Runtime.getRuntime().exec(cmd);
-
- p.waitFor();
解決方法:this
- Process p = Runtime.getRuntime().exec(cmd);
-
- StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(), "ERROR");
-
-
- errorGobbler.start();
-
- StreamGobbler outGobbler = new StreamGobbler(p.getInputStream(), "STDOUT");
-
- outGobbler.start();
-
- p.waitFor();
其中StreamGobbler類的代碼:spa
- package com.sdc.callmaxent.socket;
-
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.io.PrintWriter;
-
- import com.sdc.callmaxent.util.FileUtil;
-
-
-
-
-
-
- public class StreamGobbler extends Thread {
- InputStream is;
- String type;
- OutputStream os;
-
- StreamGobbler(InputStream is, String type) {
- this(is, type, null);
- }
-
- StreamGobbler(InputStream is, String type, OutputStream redirect) {
- this.is = is;
- this.type = type;
- this.os = redirect;
- }
-
- public void run() {
- InputStreamReader isr = null;
- BufferedReader br = null;
- PrintWriter pw = null;
- try {
- if (os != null)
- pw = new PrintWriter(os);
-
- isr = new InputStreamReader(is);
- br = new BufferedReader(isr);
- String line=null;
- while ( (line = br.readLine()) != null) {
- if (pw != null)
- pw.println(line);
- System.out.println(type + ">" + line);
- }
-
- if (pw != null)
- pw.flush();
- } catch (IOException ioe) {
- ioe.printStackTrace();
- } finally{
- FileUtil.close(pw);
- FileUtil.close(br);
- FileUtil.close(isr);
- }
- }
- }
感謝http://faq.csdn.net/read/200584.html中提到的各位。.net