Spliterator 介绍
Spliterator 接口是 Java 为了并行遍历数据源中的元素而设计的迭代器,这个可以类比最早 Java 提供的顺序遍历迭代器 Iterator,但一个是顺序遍历,一个是并行遍历。
从最早顺序遍历迭代器 Iterator 时,那个时候还是单核时代,但现在多核时代下,顺序遍历已经不能满足需求了,如何把多个任务分配到不同核上并行执行,才是能最大发挥多核的能力,所以 Spliterator 应运而生啦。
使用示例
public class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 50 ; i++) {
list.add(i+"");
}
// 分割迭代器
Spliterator spliterator = list.spliterator();
Spliterator s1 = spliterator.trySplit();
Spliterator s2 = spliterator.trySplit();
System.out.println("=============== list ================");
spliterator.forEachRemaining((i) -> System.out.print(i+" "));
System.out.println();
System.out.println("=============== s1 ================");
s1.forEachRemaining((i) -> System.out.print(i+" "));
System.out.println();
System.out.println("=============== s2 ================");
s2.forEachRemaining((i) -> System.out.print(i+" "));
System.out.println();
}
}
=============== list ================
37 38 39 40 41 42 43 44 45 46 47 48 49
=============== s1 ================
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
=============== s2 ================
25 26 27 28 29 30 31 32 33 34 35 36