天天看點

process java被阻塞_java調用process線程阻塞問題

背景

項目需求中涉及java調用.bat檔案進行圖像處理,先直接上簡略版程式

1 public voiddraw(){2

3 //調用bat腳本進行圖像處理

4 Process process = null;5 InputStream in = null;6 try{7 process = Runtime.getRuntime().exec("startup.bat");8

9 //輸出測試10 //in = process.getInputStream();11 //String line;12 //BufferedReader br = new BufferedReader(new InputStreamReader(in));13 //while ((line = br.readLine()) != null) {14 //System.out.println(line);15 //}16

17 //等待

18 process.waitFor();19

20 } catch(Exception e) {21

22 } finally{23 process.destroy();24 }25 }

JAVA使用遇到的問題描述

一般需要調用系統指令時,大部分人第一反應肯定是使用Runtime.getRuntime().exec(command)傳回一個process對象,再調用process.waitFor()來等待指令執行結束,擷取執行結果。

調試的時候發現很奇怪的現象,process.waitFor();一直沒有結束,導緻線程阻塞再次,強行關閉程式後,發現圖像處理隻進行了一部分。

于是打算列印process的輸出,看是否是圖像腳本出現異常。

在啟用輸出測試的下發代碼後,發現process的輸出一切正常,process.waitFor()一直再等待,并未結束,此時強行關閉程式後,發現圖像處理并之前多操作了一部分

根據現象并檢視了JDK的幫助文檔,如下

process java被阻塞_java調用process線程阻塞問題

是以,可以得出結論:如果外部程式不斷在向标準輸出流(對于jvm來說就是輸入流)和标準錯誤流寫資料,而JVM不讀取的話,當緩沖區滿之後将無法繼續寫入資料,最終造成阻塞在waitFor()這裡。

解決方法:在waitFor()之前,利用單獨兩個線程,分别處理process的getInputStream()和getErrorSteam(),防止緩沖區被撐滿,導緻阻塞;

修改後代碼

1 public classtest {2

3 public voiddraw(){4

5 //調用bat腳本進行圖像處理

6 Process process = null;7 InputStream in = null;8 try{9 process = Runtime.getRuntime().exec("startup.bat");10

11 //輸出測試12 //in = process.getInputStream();13 //String line;14 //BufferedReader br = new BufferedReader(new InputStreamReader(in));15 //while ((line = br.readLine()) != null) {16 //System.out.println(line);17 //}18 //新啟兩個線程

19 newDealProcessSream(process.getInputStream()).start();20 newDealProcessSream(process.getErrorStream()).start();21

22 process.waitFor();23

24 } catch(Exception e) {25

26 } finally{27 process.destroy();28 }29 }30 }

1 public class DealProcessSream extendsThread {2 privateInputStream inputStream;3

4 publicDealProcessSream(InputStream inputStream) {5 this.inputStream =inputStream;6 }7

8 public voidrun() {9 InputStreamReader inputStreamReader = null;10 BufferedReader br = null;11 try{12 inputStreamReader = newInputStreamReader(13 inputStream);14 br = newBufferedReader(inputStreamReader);15 //列印資訊16 //String line = null;17 //while ((line = br.readLine()) != null) {18 //System.out.println(line);19 //}20 //不列印資訊

21 while (br.readLine() != null);22 } catch(IOException ioe) {23 ioe.printStackTrace();24 }finally{25 try{26 br.close();27 inputStreamReader.close();28 } catch(IOException e) {29 e.printStackTrace();30 }31 }32

33 }34 }

原文:https://www.cnblogs.com/MacrossFT/p/12038479.html