List的spliterator()方法使用

List的spliterator()是JDK1.8添加的方法,这个方法允许我们对一个集合对象中的元素进行分割,分割成多个小的集合对象,然后使用多线程并发处理,从而提升对集合的处理效率。

看demo:

/**
 * ArrayList 并发迭代器使用方法
 */
public class TestArrayListIterator {

    private static int LOOP_SIZE = 100;

    public static void main(String[] args) throws Exception {
        List<String> list = new ArrayList<>();
        for(int i=0; i<LOOP_SIZE; i++) {
            list.add(i+"-"+i);
        }
        Spliterator<String> spliterator = list.spliterator();
        spliteratorList(spliterator);
        Thread.sleep(10000);
    }

    public static void spliteratorList(Spliterator<String> splList) {
        if(splList.estimateSize()>10) {
            Spliterator<String> stringSpliterator = splList.trySplit();
            spliteratorList(splList);
            spliteratorList(stringSpliterator);
            return;
        }
        new Thread(()->{
            splList.forEachRemaining(x->System.out.println(Thread.currentThread().getName() + ":" + x));
        }).start();
        return;
    }
}
/* 输出
Thread-0:93-93
Thread-12:18-18
Thread-12:19-19
Thread-12:20-20
Thread-12:21-21
Thread-12:22-22
Thread-12:23-23
Thread-12:24-24
Thread-11:25-25
Thread-11:26-26
Thread-10:31-31
Thread-10:32-32
Thread-10:33-33
Thread-10:34-34
Thread-10:35-35
Thread-10:36-36
Thread-15:0-0
Thread-15:1-1
Thread-15:2-2
Thread-15:3-3
Thread-15:4-4
Thread-15:5-5
Thread-6:56-56
Thread-6:57-57
Thread-6:58-58
Thread-6:59-59
Thread-6:60-60
Thread-6:61-61
Thread-9:37-37
Thread-9:38-38
Thread-9:39-39
Thread-9:40-40
Thread-9:41-41
Thread-9:42-42
Thread-13:12-12
Thread-13:13-13
Thread-13:14-14
Thread-13:15-15
Thread-13:16-16
Thread-13:17-17
Thread-3:75-75
Thread-3:76-76
Thread-3:77-77
Thread-3:78-78
Thread-2:81-81
Thread-2:82-82
Thread-2:83-83
Thread-2:84-84
Thread-2:85-85
Thread-2:86-86
Thread-4:68-68
Thread-4:69-69
Thread-4:70-70
Thread-4:71-71
Thread-4:72-72
Thread-4:73-73
Thread-4:74-74
Thread-7:50-50
Thread-7:51-51
Thread-7:52-52
Thread-7:53-53
Thread-7:54-54
Thread-7:55-55
Thread-5:62-62
Thread-1:87-87
Thread-1:88-88
Thread-5:63-63
Thread-5:64-64
Thread-5:65-65
Thread-5:66-66
Thread-5:67-67
Thread-3:79-79
Thread-3:80-80
Thread-11:27-27
Thread-11:28-28
Thread-11:29-29
Thread-11:30-30
Thread-0:94-94
Thread-0:95-95
Thread-0:96-96
Thread-0:97-97
Thread-0:98-98
Thread-0:99-99
Thread-14:6-6
Thread-14:7-7
Thread-14:8-8
Thread-14:9-9
Thread-14:10-10
Thread-14:11-11
Thread-8:43-43
Thread-8:44-44
Thread-8:45-45
Thread-8:46-46
Thread-8:47-47
Thread-8:48-48
Thread-8:49-49
Thread-1:89-89
Thread-1:90-90
Thread-1:91-91
Thread-1:92-92
 */

这里的List中添加了100个元素,调用spliterator()方法进行分割,只要集合中的元素大于10个,就进行拆分。

分割是将集合一分为二,通过递归不停的调用自己,直到拆分的集合大小不大于10,则开始执行后续逻辑。