当前位置: 编程技术>java/j2ee
Java 进程执行外部程序造成阻塞的一种原因
来源: 互联网 发布时间:2014-11-04
本文导语: 查了好多资料,差点就动手翻Java源码了,最后结合一篇文章(忘记出处了),想到了输出流会阻塞进程执行。 Java进程执行有一个输入流,两个输出流(相对于外部程序)。当两个输出流有内容输出,而Java执行程序没有及时清空...
查了好多资料,差点就动手翻Java源码了,最后结合一篇文章(忘记出处了),想到了输出流会阻塞进程执行。 Java进程执行有一个输入流,两个输出流(相对于外部程序)。当两个输出流有内容输出,而Java执行程序没有及时清空输出流时就会阻塞进程。
现贴出代码,希望能帮助到有需要的同行:
现贴出代码,希望能帮助到有需要的同行:
代码如下:
/**
* pdf转swf函数
* @param path 输入输出文件路径
* @param inputFileName 输入文件名
* @param outputFileName 输出文件名
* @return File 生成的swf文件
*/
private static File toSwf(String sourceFile, String destFile, String command) {
long beginTime = System.nanoTime();
Runtime rt = Runtime.getRuntime();
try {
Process process = rt.exec(command);
final InputStream isNormal = process.getInputStream();
new Thread(new Runnable() {
public void run() {
BufferedReader br = new BufferedReader(new InputStreamReader(isNormal));
StringBuilder buf = new StringBuilder();
String line = null;
try {
while((line = br.readLine()) != null){
buf.append(line + "n");
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("输出结果为:" + buf);
}
}).start(); // 启动单独的线程来清空process.getInputStream()的缓冲区
InputStream isError = process.getErrorStream();
BufferedReader br2 = new BufferedReader(new InputStreamReader(isError));
StringBuilder buf = new StringBuilder();
String line = null;
while((line = br2.readLine()) != null){
buf.append(line + "n");
}
System.out.println("错误输出结果为:" + buf);
try {
process.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
* pdf转swf函数
* @param path 输入输出文件路径
* @param inputFileName 输入文件名
* @param outputFileName 输出文件名
* @return File 生成的swf文件
*/
private static File toSwf(String sourceFile, String destFile, String command) {
long beginTime = System.nanoTime();
Runtime rt = Runtime.getRuntime();
try {
Process process = rt.exec(command);
final InputStream isNormal = process.getInputStream();
new Thread(new Runnable() {
public void run() {
BufferedReader br = new BufferedReader(new InputStreamReader(isNormal));
StringBuilder buf = new StringBuilder();
String line = null;
try {
while((line = br.readLine()) != null){
buf.append(line + "n");
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("输出结果为:" + buf);
}
}).start(); // 启动单独的线程来清空process.getInputStream()的缓冲区
InputStream isError = process.getErrorStream();
BufferedReader br2 = new BufferedReader(new InputStreamReader(isError));
StringBuilder buf = new StringBuilder();
String line = null;
while((line = br2.readLine()) != null){
buf.append(line + "n");
}
System.out.println("错误输出结果为:" + buf);
try {
process.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
long endTime = System.nanoTime();
System.out.println("转swf耗时: " + (endTime - beginTime) / 1000000000 + " 秒 " + sourceFile);
return new File(destFile);
}