2
我正在使用ProcessBuilder启动外部进程,但我需要能够杀死它。现在我没有任何问题可以终止进程,但由于某种原因,错误流不会关闭,因此读取流的线程永远不会结束。这使我无法关闭我的程序。Java停止进程和关闭流
这里是我开始从输入和错误流中读取线程的地方。
final Thread inputPrinter = new Thread() {
public void run() {
BufferedReader inputStream = new BufferedReader(new InputStreamReader(builder.getInputStream()));
String line;
try {
while ((line = inputStream.readLine()) != null) {
Util.println(line, false);
}
} catch (IOException e) {
} finally {
Util.println("input end");
try {
inputStream.close();
} catch (IOException e) {
}
}
}
};
inputPrinter.start();
Thread errorPrinter = new Thread() {
public void run() {
BufferedReader errorStream = new BufferedReader(new InputStreamReader(builder.getErrorStream()));
String line;
try {
while ((line = errorStream.readLine()) != null) {
Util.println(line, true);
}
} catch (IOException e) {
} finally {
Util.println("error end");
try {
errorStream.close();
} catch (IOException e) {
}
}
}
};
errorPrinter.start();
builder.waitFor();
Util.println("");
Util.println("Finished building project.");
这是我的代码,用于停止进程。
try {
builder.getOutputStream().close();
builder.getInputStream().close();
builder.getErrorStream().close();
} catch (IOException e) {
e.printStackTrace();
}
builder.destroy();
Util.println("");
Util.println("Build aborted by user.", true);
当我试图停止该过程时,我得到以下打印。
构建由用户中止。
已完成的建筑物项目。
输入端
我从来没有得到“错误结束”和调试程序显示了线程只是坐在“的readLine()”。
等待进程的代码运行在它自己的线程中(与杀死进程的代码分开)。
我需要做些什么来确保errorPrinter线程死亡?
如果在调用destroy之前不关闭流,会发生什么? – assylias
什么是所有空的catch块?你知道这不仅仅是坏代码,它是彻头彻尾的**危险**代码。 –
如果我之前没有在流上关闭,则会发生完全相同的情况。 如果我不在乎它是否停止,为什么空的catch块危险? – EmbMicro