使用parallelStream代码
public static void main(String[] args) { Listids1 = Lists.newArrayList(); List ids2 = Lists.newArrayList(); for(int i = 0; i < 1000; i ++){ ids1.add(i); } ids1.parallelStream().forEach(id ->ids2.add(id)); }
结果:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 823 at java.util.ArrayList.add(ArrayList.java:459) at com.test.lambda$main$0(Md5Util.java:51) at com.test$$Lambda$1/399573350.accept(Unknown Source) at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183) at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1374) at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:512) at java.util.stream.ForEachOps$ForEachTask.compute(ForEachOps.java:290) at java.util.concurrent.CountedCompleter.exec(CountedCompleter.java:731) at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289) at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:902) at java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1689) at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1644) at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
因为parallelStream是并发流,当使用线程不安全的list的时候可能导致数组越界,可以使用线程安全的list,如下所示
Listids2 = Collections.synchronizedList(Lists.newArrayList());
如果使用 stream()方法,单线程处理也可以