gpt4 book ai didi

java - 结束卡在 InputStream.read() 循环中的线程

转载 作者:行者123 更新时间:2023-11-30 08:29:36 29 4
gpt4 key购买 nike

我启动了一个 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 一个 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并退出。您不必自己做任何特别的事情。

编辑 在我看来,通过阅读您对其他答案的评论,您的真正问题在于结束流程。一旦发生这种情况,这些线程就会松开。你在攻击问题的错误一端。

关于java - 结束卡在 InputStream.read() 循环中的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19280595/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com