通过parallelStream多线程异步任务执行提高代码运行效率

parallelStream().peek()的使用

public static void main(String[] args) throws ExecutionException, InterruptedException {
    LinkedList<Map<Integer, Integer>> list =new LinkedList<>();
    for (int i=1;i<10000;i++){
        Map<Integer, Integer> map = new HashMap<>();
        map.put(1,0);
        list.add(map);
    }
    long time1 = System.currentTimeMillis();
    Test1(list);
    long time2 = System.currentTimeMillis();
    System.out.println("Test1耗时"+(time2-time1));
    Test2(list);
    long time3 = System.currentTimeMillis();
    System.out.println("Test2耗时"+(time3-time2));
    Test3(list);
    long time4 = System.currentTimeMillis();
    System.out.println("Test3耗时"+(time4-time3));
}

//使用单线程处理
private static void Test1(LinkedList<Map<Integer, Integer>> list) {
    list.forEach(map ->{
        map.put(1,2);
        try {
            //模拟业务耗时
            TimeUnit.MILLISECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
}
缺点:
线程数量和CPU核数一致
需要等待线程全部执行完毕,主线程(调用线程)才继续往下执行
共享线程池,不能对不同任务分别设定线程池大小(其实真实业务也不需要)

//使用默认线程池的parallelStream
private static void Test2(LinkedList<Map<Integer, Integer>> list) {
    list.parallelStream().peek(map ->{
        map.put(1,2);
        try {
            //模拟业务耗时
            TimeUnit.MILLISECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }).collect(Collectors.toList());

}

//使用ForkJoinPool自定义线程池的parallelStream
private static void Test3(LinkedList<Map<Integer, Integer>> list) throws ExecutionException, InterruptedException {
    ForkJoinPool pool = new ForkJoinPool(500);
    pool.submit(() -> list.parallelStream().peek(map -> {
        map.put(1,2);
        try {
            //模拟业务耗时
            TimeUnit.MILLISECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }).collect(Collectors.toList())).get();
}
该方式中,主进程(调用线程)不会等parallelStream流执行完毕。如需等待,使用future.get()方法阻塞;

我们创建自己的线程池,所以(1)可以避免共享线程池,(2)可以分配比处理机数量更多的线程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值