Java:多个线程同时读取同一个InputStream
Java: multiple threads read the same InputStream at the same time
有private InputStream inputStream;
。现在,我想将 inputStream 分成 10 个块,return 另外 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);
}
...但差异纯粹是装饰性的。
有private InputStream inputStream;
。现在,我想将 inputStream 分成 10 个块,return 另外 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);
}
...但差异纯粹是装饰性的。