JAVA创建子进程并处理waitFor() 阻塞问题
生活随笔
收集整理的這篇文章主要介紹了
JAVA创建子进程并处理waitFor() 阻塞问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
雖然很想休息,但是想想還是要把今天學的東西記下來,不然以后再用還是新知識。
新建一個線程類讀取子進程的匯報信息和錯誤信息,避免阻塞
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
總結
以上是生活随笔為你收集整理的JAVA创建子进程并处理waitFor() 阻塞问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 常见木马病毒名称
- 下一篇: html生成二维码,qr