Java8 遍历List 使用stream().parallel()并发安全

1. parallelStream是什么:

复制代码
 java 8引入了并行流的概念来进行并行处理,而并行流(Parallel Stream)利用所有可用CPU内核的优势,并行处理任务。其原理(Parallel Stream)是可以把大任务分成多个小任务执行, 最后再把执行结果进行合并, ForkJoinPool用工作窃取算法实现。

2.Java8的paralleStream是线程安全吗

复制代码
    一个简单例子,循环1000000次,往list中插入数据,最后看list的长度。
javascript 复制代码
public class TestParallel {
    public static void main(String[] args) {
        StopWatch stopWatch = new StopWatch();
        List<Integer> list = new ArrayList<>();
        stopWatch.start("TaskOneName");
        IntStream.range(0, 1000000).forEach(list::add);
        stopWatch.stop();
        System.out.println("list size:" + list.size());
        System.out.println("当前任务名称:" + stopWatch.currentTaskName() +" 执行时间:" + stopWatch.getTotalTimeMillis());
 
    }
}

执行时间以及list 中的size见下图

使用并发流

javascript 复制代码
public class TestParallel {
   public static void main(String[] args) {
       StopWatch stopWatch = new StopWatch();
       List<Integer> list = new ArrayList<>();
       stopWatch.start("TaskOneName");
       IntStream.range(0, 10000).parallel().forEach(list::add);
       stopWatch.stop();
       System.out.println("list size:" + list.size());
       System.out.println("当前任务名称:" + stopWatch.currentTaskName() +" 执行时间:" + stopWatch.getTotalTimeMillis());

   }
}

执行情况一:

执行情况二:

从上图可看出,list的add操作并非我们想要的结果。

3.如果非要用并行流怎么办

加锁吧。

javascript 复制代码
public class TestParallel {
    public static void main(String[] args) {
        StopWatch stopWatch = new StopWatch();
        List<Integer> list = new ArrayList<>();
        stopWatch.start("TaskOneName");
         Lock lock = new ReentrantLock();
        IntStream.range(0, 10000).parallel().forEach(adata->{
            lock.lock();
            try {
                list.add(adata);
            }finally {
                lock.unlock();
            }
        });
        stopWatch.stop();
        System.out.println("list size:" + list.size());
        System.out.println("当前任务名称:" + stopWatch.currentTaskName() +" 执行时间:" + stopWatch.getTotalTimeMillis());
 
    }
}

执行结果:

4.使用线程安全的ArrayList:

使用线程安全的ArrayList: CopyOnWriteArrayList

相关推荐
埃博拉酱3 天前
VS Code Remote SSH 连接 Windows 服务器卡在"下载 VS Code 服务器":prcdn DNS 解析失败的诊断与 BITS 断点续传
windows·ssh·visual studio code
唐宋元明清21884 天前
.NET 本地Db数据库-技术方案选型
windows·c#
加号34 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
琢磨先生David4 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
tryCbest4 天前
Windows环境下配置pip镜像源
windows·pip
呉師傅4 天前
火狐浏览器报错配置文件缺失如何解决#操作技巧#
运维·网络·windows·电脑
百事牛科技4 天前
保护文档安全:PDF限制功能详解与实操
windows·pdf
一个人旅程~4 天前
如何用命令行把win10/win11设置为长期暂停更新?
linux·windows·经验分享·电脑
qq_454245034 天前
基于组件与行为的树状节点系统
数据结构·c#
超级大福宝4 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode