Java 进程执行外部程序造成阻塞的一种原因
程序员文章站
2024-02-24 19:12:46
查了好多资料,差点就动手翻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);
}
上一篇: spring boot 自动更新静态文件和后台代码的实例
下一篇: Java编程实现验证哥德巴赫猜想