![](/img/trans.png)
[英]Java class to allow multiple threads to read or one to modify at the same time
[英]Java: multiple threads read the same InputStream at the same time
有private InputStream inputStream;
。 现在,我想将inputStream分成10个块,这将返回另外10个InputStream。 10个线程将同时读取10个InputStream。 这个怎么做?
以下代码是否有效?
BoundedInputStream stream = new BoundedInputStream(inputStream, chunkSize);
该代码不符合您的想法。 BoundedInputStream
是一个流,该流限制可以从基础流读取的字节数。 但这并没有说明将返回哪些字节……如果其他线程也在从底层流中读取数据。
对于正在从非文件源读取的输入流,将流分成多个块的唯一方法是读取整个流,将其写入可以分块的内容,然后在块上打开单独的输入流。
如果源是文件,则可以打开多个独立的输入流,使用seek
或等效输入跳到所需位置并读取。 例如(基于source ):
public InputStream chunkInputStream(File file, int pos, int count) {
RandomAccessFile raf = new RandomAccessFile(file, "r");
BoundedInputStream res = new BoundedInputStream(
Channels.newInputStream(raf.getChannel().position(pos)),
count);
// res.setPropagateClose(false) ; // INCORRECT!
return res ;
}
实际上,您可以避免使用RandomAccessFile
并执行以下操作:
public InputStream chunkInputStream(File file, int pos, int count) {
FileChannel channel = FileChannel.open(file, READ);
return new BoundedInputStream(
Channels.newInputStream(channel.position(pos)),
count);
}
...但是区别纯粹是表面上的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.