这里的问题是Spliterator
来自Iterable
, 没有已知的大小。所以内部实现会将元素缓冲到一个大小1024
的缓冲区中,并在下一次迭代中继续增加缓冲区。我的意思是:
List<Integer> coll = IntStream.range(0, 150_000).boxed().collect(Collectors.toList());
Iterable<List<Integer>> it = Iterables.partition(coll, 1);
Spliterator<List<Integer>> sp = it.spliterator();
Spliterator<List<Integer>> one = sp.trySplit();
System.out.println(one.getExactSizeIfKnown());
Spliterator<List<Integer>> two = sp.trySplit();
System.out.println(two.getExactSizeIfKnown());
Spliterator<List<Integer>> three = sp.trySplit();
System.out.println(three.getExactSizeIfKnown());
Spliterator<List<Integer>> four = sp.trySplit();
System.out.println(four.getExactSizeIfKnown());
这将打印:
1024
2048
3072
4096
如果你想5000
一次处理元素,你需要从Spliterator
一个已知大小的开始。您可以将这些分区ArrayList
放在首位:
public static void main(String[] args) {
List<Integer> coll = IntStream.range(0, 15_000).boxed().collect(Collectors.toList());
Iterable<List<Integer>> it = Iterables.partition(coll, 5000);
List<List<Integer>> list = new ArrayList<>();
it.forEach(list::add);
StreamSupport.stream(list.spliterator(), true)
.map(x -> {
System.out.println(
"Thread : " + Thread.currentThread().getName() +
" processed elements in the range : " + x.get(0) + " , " + x.get(x.size() - 1)
);
return x;
})
.flatMap(List::stream)
.collect(Collectors.toList());
}
在我的机器上,它显示它们每个都由一个线程处理:
Thread : ForkJoinPool.commonPool-worker-5 processed elements in the range : 10000 , 14999
Thread : ForkJoinPool.commonPool-worker-19 processed elements in the range : 0 , 4999
Thread : main processed elements in the range : 5000 , 9999