windows环境下,JAVA调用Runtime.getRuntime()执行命令时线程阻塞的解决办法

最近在使用JAVA调用Runtime.getRuntime()执行数据库备份命令时,发现一直不成功,调试时总是阻塞在读取输出的地方,代码如下:

Runtime rt = Runtime.getRuntime();

Process pr = rt.exec(command, null, new File(mebInstallPath));

BufferedReader buffer = new BufferedReader(new InputStreamReader(pr.getInputStream()));

String line = null;
while ((line = buffer.readLine()) != null) {
System.out.println(line);
}
int exitVal = pr.waitFor();

System.out.println("Exited with error code " + exitVal);

执行到while循环的地方就阻塞了,百思不得其解,最后看到了haozhugogo发的帖子(https://blog.csdn.net/haozhugogo/article/details/78363930)之后,才意识到问题所在。问题确实如他所说,因为我执行的备份命令产生的标准输出比较多,而标准输出缓冲区不够大,由于缓冲区的问题,由于java进程没有清空写到缓冲区的内容,结果导致程序一直在等待。

最后修改后,程序运行正常

                        InputStream is2 = null;
BufferedReader br2 = null;
try 
{
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command, null, new File(mebInstallPath));

final InputStream is1 = pr.getInputStream();
new Thread(new Runnable() {
public void run() {
BufferedReader br = new BufferedReader(new InputStreamReader(is1));
try {
while (br.readLine() != null)
;
} catch (Exception e) {


e.printStackTrace();
}
finally
{
try {
br.close();
is1.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start(); // 启动单独的线程来清空p.getInputStream()的缓冲区
is2 = pr.getErrorStream();
br2 = new BufferedReader(new InputStreamReader(is2));
String line = null;
while ((line = br2.readLine()) != null)
System.out.println(line); 
int exitVal = pr.waitFor();
System.out.println("Exited with error code " + exitVal);

} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
finally
{
try {
br2.close();
is2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

在此感谢haozhugogo,本文也作为自己的备忘吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值