我启动一个通过此SyncPipe Runnable输出到System.out的cmd应用程序:
public class SyncPipe implements Runnable {
private final InputStream is;
private final OutputStream os;
public SyncPipe(InputStream is, OutputStream os) {
this.is = is;
this.os = os;
}
public void run() {
try {
final byte[] buffer = new byte[1024];
for ( int length = 0; ( length = is.read(buffer) ) != -1; )
os.write(buffer, 0, length);
System.out.print("stopped");
} catch ( Exception ex ) {
ex.printStackTrace();
}
}
}
我用
cmd = "C:/bin/read.exe -f D:/test.jpg"
启动RunItprivate class RunIt implements Runnable {
public int p;
public String cmd;
public RunIt (int p, String cmd) {
this.p = p;
this.cmd = cmd;
}
public void run() {
ProcessBuilder pb = new ProcessBuilder("cmd");
try {
process = pb.start();
(new Thread(new SyncPipe(process.getErrorStream(), System.err))).start();
(new Thread(new SyncPipe(process.getInputStream(), System.out))).start();
OutputStream out = process.getOutputStream();
out.write((cmd + "\r\n").getBytes());
out.flush();
out.close();
try {
process.waitFor();
} catch ( InterruptedException e ) {
e.printStackTrace();
}
println("Stopped using %d.", p);
} catch ( IOException ex ) {
ex.printStackTrace();
}
}
}
我现在的问题是:如何使
(new Thread(new SyncPipe(process.getErrorStream(), System.err)))
死亡?给SyncPipe一个 boolean 变量stop
,在运行时将其设置为true
,然后通过for ( int length = 0; ( length = is.read(buffer) ) != -1 && !stop; )
检查它并不能解决问题。在此先多谢。
我最终完成了@Gray建议的解决方法。现在可以使用:
public void run() {
try {
final byte[] buffer = new byte[1024];
do
if ( is.available() > 0 ) {
int length = is.read(buffer);
if ( length != -1 )
os.write(buffer, 0, length);
else
stop = true;
}
while ( !stop );
} catch ( Exception ex ) {
ex.printStackTrace();
}
}
最佳答案
该线程将读取EOS并在基础进程退出时退出。您不必自己为此做任何特别的事情。
编辑在我看来,从阅读您的评论到其他答案后,您真正的问题正在结束这一过程。这些线程将在发生这种情况时立即松开。您正在解决问题的错误结局。