list.stream().parallel() 并行流
https://blog.csdn.net/u011001723/article/details/52794455/ : parallel()其实就是一个并行执行的流.它通过默认的ForkJoinPool,可能提高你的多线程任务的速度.
https://www.cnblogs.com/strivelearn/p/6005649.html :并发与并行的区别
Java 8 lambda stream forEach parallel 等循环与Java 7 for each 循环耗时测试: 转自:https://blog.csdn.net/qq_27093465/article/details/77770479
Java 8 里面的stream 有串行流和并行流之分。
说高级的stream就是那个并行流。下面是那个并行流的简单实现。只要是继承Collection类的都可以这么用。
list.stream().parallel()
list.parallelStream()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | package com.lxk.lambdaTest; import com.google.common.collect.Lists; import java.util.List; /** * 测试性能(Java 8 的循环和Java 7 的循环耗时的对比测试) * <p> * Created by lxk on 2017/8/31 */ public class Performance { public static void main(String[] args) { List<String> list = getLoopList(); normalBeforeLoop(list); normalAfterLoop(list); notNormalAfterLoop(list); } private static void notNormalAfterLoop(List<String> list) { long a = System.currentTimeMillis(); list.stream().parallel().forEach(System.out::print); System.out.println( " list.stream().parallel().forEach 执行耗时 : " + (System.currentTimeMillis() - a) / 1000f + " 秒 " ); } private static void normalAfterLoop(List<String> list) { long a = System.currentTimeMillis(); list.stream().forEach(System.out::print); System.out.println( " list.stream().forEach 执行耗时 : " + (System.currentTimeMillis() - a) / 1000f + " 秒 " ); a = System.currentTimeMillis(); list.forEach(System.out::print); System.out.println( " list.forEach 执行耗时 : " + (System.currentTimeMillis() - a) / 1000f + " 秒 " ); } private static void normalBeforeLoop(List<String> list) { long a = System.currentTimeMillis(); for (String s : list) { System.out.print(s); } System.out.println( " for each 执行耗时 : " + (System.currentTimeMillis() - a) / 1000f + " 秒 " ); } private static List<String> getLoopList() { List<String> list = Lists.newArrayList(); for ( int i = 0 ; i < 10000 ; i++) { list.add( "item " + i); } return list; } } |
好,关于,那个并行和串行的流的差别,可以看到啦。
并行的流,在循环的时候,就不是 1 - 9999 挨着输出。而是,看多核的心情。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步