我有两个线程。其中一个写入 PipedOutputStream,另一个从相应的 PipedInputStream 读取。背景是一个线程正在从远程服务器下载一些数据,并通过管道流将其复用到多个其他线程。
问题是有时(尤其是下载大文件时)(>50Mb)文件)我得到java.io.IOException:管道损坏当尝试从 PipedInputStream 读取时。
Javadoc 说A pipe is said to be broken if a thread that was providing data bytes to the connected piped output stream is no longer alive.
确实如此,我的写线程在将他的所有数据写入PipedOutputStream后确实死掉了。
有什么解决办法吗?如何防止 PipedInputStream 抛出此异常?我希望能够读取写入 PipedOutputStream 的所有数据,即使写入线程完成了工作。 (如果有人知道如何保持写入线程处于活动状态直到读取所有数据,那么这个解决方案也是可以接受的).
使用 java.util.concurrent.CountDownLatch,并且在第二个线程发出已完成从管道读取的信号之前不要结束第一个线程。
更新:快速而肮脏的代码来说明我下面的评论
final PipedInputStream pin = getInputStream();
final PipedOutputStream pout = getOutputStream();
final CountDownLatch latch = new CountDownLatch(1);
InputStream in = new InputStream() {
@Override
public int read() throws IOException {
return pin.read();
}
@Override
public void close() throws IOException {
super.close();
latch.countDown();
}
};
OutputStream out = new OutputStream(){
@Override
public void write(int b) throws IOException {
pout.write(b);
}
@Override
public void close() throws IOException {
while(latch.getCount()!=0) {
try {
latch.await();
} catch (InterruptedException e) {
//too bad
}
}
super.close();
}
};
//give the streams to your threads, they don't know a latch ever existed
threadOne.feed(in);
threadTwo.feed(out);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)