【发布时间】:2013-10-09 19:11:52
【问题描述】:
我启动一个 cmd 应用程序,通过这个 SyncPipe Runnable 输出到 System.out:
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"启动RunIt
private 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 一个布尔变量 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();
}
}
【问题讨论】:
标签: java multithreading cmd destroy