【发布时间】:2019-01-05 02:11:37
【问题描述】:
我的代码:
public ArrayList<InputStream> getAllInputStreams() {
ArrayList<InputStream> allStreams = new ArrayList<InputStream>();
InputStream stream = this.getNext();
while (stream != null) {
allStreams.add(stream);
stream = this.getNext();
}
return allStreams;
}
public InputStream getNext() {
if (done()) {
return null;
}
InputStream segment = createInputStream();
this.countStream++;
return segment;
}
protected InputStream createInputStream() {
BoundedInputStream res = new BoundedInputStream(
Channels.newInputStream(this.randomAccessFile.getChannel().position(this.countStream * chunkSize)), chunkSize);
res.setPropagateClose(false) ;
return res ;
}
我正在尝试将file 拆分为多个 InputStream(s) (private RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");。所有 InputStream(s) (来自getAllInputStreams()) 以由多个线程处理,似乎它们中的大多数都是空的。为什么?
欢迎任何提示。谢谢
更新
以下代码似乎工作正常。下面的一段代码是将文件分成几个夹头的好方法吗?每个卡盘的大小应该小于内存大小吗?
protected InputStream createInputStream() {
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
BoundedInputStream res = new BoundedInputStream(
Channels.newInputStream(randomAccessFile.getChannel().position(this.countStream * chunkSize)), chunkSize);
res.setPropagateClose(false) ;
return res ;
}
【问题讨论】:
-
if (done()) { return null;因为大部分都“完成”了?真的,我看不出我们如何从您显示的代码中分辨出来。 -
是什么让您认为使用从同一 IO 设备读取的多个流,只是在不同的位置会加速事情?根据底层硬件和软件堆栈,您实际上可能会看到速度变慢。因为您对相同 IO 设备的真正随机读取访问会产生大量开销。
-
@GhostCat,那么,有什么办法可以加快速度吗?谢谢
标签: java multithreading file inputstream