雖然很想休息,但是想想還是要把今天學的東西記下來,不然以后再用還是新知識。
新建一個線程類讀取子進程的匯報信息和錯誤信息,避免阻塞
class StreamGobbler extends Thread { InputStream is; String type; 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) System.out.println(type + ">" + line); } catch (IOException ioe) { ioe.printStackTrace(); } } }
創建子進程的RUN方法
//cmd命令 String s = "I:/OpenModelica-v1.9.7/bin/omc.exe "+courseFile+"/modelica/tcs.mos"; //執行cmd命令 Process proc = Runtime.getRuntime().exec(s); //接收子進程的匯報信息和錯誤信息,避免阻塞 new StreamGobbler(proc.getInputStream(),"INFO").start(); new StreamGobbler(proc.getErrorStream(),"ERROR").start(); //獲取子進程執行結果狀態 int status=proc.waitFor(); if (status == 0){ System.out.println(n+"執行完畢"); detect(n); }else System.out.println(n+"執行失敗"); //銷毀子進程 proc.destroy();
注:JAVA進程waitFor() 阻塞總結參照博客https://blog.csdn.net/jinhao2003/article/details/2136919