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
posted on 2019-01-02 21:29 Pusteblume2018 阅读(1539) 评论(0) 编辑 收藏 举报