位置:首页 » 文章/教程分享 » 多线程Runtime.getRuntime().exec异常终止的问题
Java调用一个bat批处理程序,调用几十次后会莫名的不再执行,无任何异常抛出。千试万试,LOG精细到逐行,只知道走到Runtime.getRuntime().exec()程序就停止了,但打死不知道为什么。那真以为里面有鬼。后来寻摸着Runtime.getRuntime().exec()有问题,真给我找到答案了。

大概原因是,调用Runtime.getRuntime().exec()后,如果不及时捕捉进程的输出,会导致JAVA挂住,看似被调用进程没退出。所以,解决办法是,启动进程后,再启动两个JAVA线程及时的把被调用进程的输出截获。

一下子,整个世界清爽多了。。。

原先程序只有一句:Runtime.getRuntime().exec(strMakePathPath);

后来程序更改为:
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();  
        }  
    }  
}
调用如下:
Process proc = Runtime.getRuntime().exec(strMakePathPath);  
StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "Error");  
StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "Output");  
errorGobbler.start();  
outputGobbler.start();  
proc.waitFor();