Home
  • 计算机网络
  • 操作系统
  • 数据结构与算法
  • 设计模式
  • JavaSE
  • JVM
  • JUC
  • Netty
  • CPP
  • QT
  • UE
  • Go
  • Gin
  • Gorm
  • HTML
  • CSS
  • JavaScript
  • vue2
  • TypeScript
  • vue3
  • react
  • Spring
  • SpringMVC
  • Mybatis
  • SpringBoot
  • SpringSecurity
  • SpringCloud
  • Mysql
  • Redis
  • 消息中间件
  • RPC
  • 分布式锁
  • 分布式事务
  • 个人博客
  • 弹幕视频平台
  • API网关
  • 售票系统
  • 消息推送平台
  • SaaS短链接系统
  • Linux
  • Docker
  • Git
GitHub (opens new window)
Home
  • 计算机网络
  • 操作系统
  • 数据结构与算法
  • 设计模式
  • JavaSE
  • JVM
  • JUC
  • Netty
  • CPP
  • QT
  • UE
  • Go
  • Gin
  • Gorm
  • HTML
  • CSS
  • JavaScript
  • vue2
  • TypeScript
  • vue3
  • react
  • Spring
  • SpringMVC
  • Mybatis
  • SpringBoot
  • SpringSecurity
  • SpringCloud
  • Mysql
  • Redis
  • 消息中间件
  • RPC
  • 分布式锁
  • 分布式事务
  • 个人博客
  • 弹幕视频平台
  • API网关
  • 售票系统
  • 消息推送平台
  • SaaS短链接系统
  • Linux
  • Docker
  • Git
GitHub (opens new window)
  • 线程

  • 共享模型

  • 非共享模型

  • 并行

    • 函数式编程
    • 映射归约
      • 并行流
        • parallel
        • parallelStream
  • 多线程设计模式

  • JUC
  • 并行
Nreal
2023-11-01
目录

映射归约

# 并行流

并行流将任务分配给多个线程完成;

# parallel

parallel方法将串行流转换为并行流;

public class Parallel_test {
    public static void main(String[] args) {
        Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9);
        Integer sum = stream.parallel().peek(new Consumer<Integer>(){
                    @Override
                    public void accept(Integer num) {
                        System.out.println(num+Thread.currentThread().getName());
                    }
                }).filter(num->num>5)
                .reduce((result,ele)->result+ele)
                .get();
        System.out.println(sum);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

输出:

6main 3ForkJoinPool.commonPool-worker-9 5main 4ForkJoinPool.commonPool-worker-9 1main 7ForkJoinPool.commonPool-worker-4 9ForkJoinPool.commonPool-worker-13 8ForkJoinPool.commonPool-worker-2 2ForkJoinPool.commonPool-worker-11 30

# parallelStream

获取并行流对象;

List<Author> authors = getAuthors();
authors.parallelStream()
        .map(author -> author.getAge())
        .map(age -> age + 10)
        .filter(age->age>18)
        .map(age->age+2)
        .forEach(System.out::println);
1
2
3
4
5
6
7
函数式编程
生产消费者模式

← 函数式编程 生产消费者模式→

Theme by Vdoing | Copyright © 2021-2024
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式