代码之家  ›  专栏  ›  技术社区  ›  BAE

Java:多个线程同时读取同一个InputStream

  •  0
  • BAE  · 技术社区  · 6 年前

    private InputStream inputStream; . 现在,我想将inputStream分成10个块,这将返回另外10个inputStream。10个线程将同时读取10个InputStream。怎么做?

    以下代码有效吗?

    BoundedInputStream stream = new BoundedInputStream(inputStream, chunkSize);
    
    1 回复  |  直到 6 年前
        1
  •  4
  •   Stephen C    6 年前

    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);
    }
    

    ... 但这些差异纯粹是表面上的。