1. 程式人生 > >Runtime.getRuntime().exec()程序阻塞問題

Runtime.getRuntime().exec()程序阻塞問題

今天在用Runtime.getRuntime().exec()時程式碼走了一個或者兩個小時後就會自動阻塞,網上找到了原因,是因為沒有對Process的輸出資訊及時清理導致程序阻塞,服務失效。於是,在Runtime.getRuntime().exec()之後,p.waitFor()之前加入如下執行緒程式碼:

String cmds_ = "/usr/bin/pdf2htmlEX  --no-drm 1 --split-pages 1 "
						+ "--embed-css 0  --embed-javascript 0 --embed-image 0 --embed-font 0 --css-filename html.css "
						+ "--fit-width 700 --bg-format jpg   --auto-hint 1 --svg-node-count-limit 1 --auto-hint 1 "
						+ "--embed-external-font 0 --dest-dir " + htmlPath + " --page-filename "
						+ path[path.length - 1].replace(".pdf", "") + "-%d.page " + pdfPath;
				String[] cmds = { "/bin/sh", "-c", cmds_ };
				Process pro = Runtime.getRuntime().exec(cmds);
				StreamGobbler errorGobbler = new StreamGobbler(pro.getErrorStream(), "Error");
				StreamGobbler outputGobbler = new StreamGobbler(pro.getInputStream(), "Output");
				errorGobbler.start();
				outputGobbler.start();
				pro.waitFor();

StreamGobbler類:

<pre name="code" class="java">public class StreamGobbler extends Thread {  
  
    InputStream is;  
    String type;  
  
    public StreamGobbler(InputStream is, String type) {  
        this.is = is;  
        this.type = type;  
    }  
  
    public void run() {  
        try {  
            InputStreamReader isr = new InputStreamReader(is);  
            BufferedReader br = new BufferedReader(isr);  
            String line = null;  
            while ((line = br.readLine()) != null) {  
                if (type.equals("Error")) {  
                    System.out.println("Error   :" + line);  
                } else {  
                    System.out.println("Debug:" + line);  
                }  
            }  
        } catch (IOException ioe) {  
            ioe.printStackTrace();  
        }  
    }  
}