Fork Join

前言

本质其实就是分解和合并

divide-and-conquer

Fork-Join

1. fork

Result solve(Problem problem) {
	if (problem is small enough) {
			directly solve problem直接解决问题
	} else {
			split problem into independent parts 把问题分解成独立的部分
			fork new subtasks to solve each part fork 新的低级任务去解决每个小问题
			join all subtasks 将所有小问题合并
			compose results from subresults 将结果合并
}
}

Implementations of ForkJoinTask must override the compute()
RecursiveAction (no result) and RecursiveTask (returns result) are concretizations of such tasks
They can be executed by a ForkJoinPool calling its invoke() method
在这里插入图片描述在这里插入图片描述
Thread-safe Classes
Queue with operations that block if queue is full/empty when putting/retrieving an element
不同情况会block()
put(…) blocks if full
take() blocks if empty

2.Streams

提供一些对数据的常用操作
filter,
map, reduce,
collect,
findAny, findFirst,
min, max,
etc.
在这里插入图片描述
在这里插入图片描述

Streams: The collect Operation

A collect operation performs a reduction given three arguments:
Supplier: Delivers a new result container 传送了一个新的返回值储存容器
Accumulator: A function for incorporating a new element in the result
一个函数来将新的元素纳入结果中
Combiner: Combines two values and must be compatible with the result
将两个值结合 并使他与结果兼容

R collect(
Supplier supplier,
BiConsumer<R, ? super T> accumulator,
BiConsumer<R, R> combiner);

在这里插入图片描述

Map<Integer, List> groupedByAge =
personsInAuditorium
.stream()
.collect(Collectors.groupingBy(Person::getAge));

Parallel Streams

这些操作都可以并行运行

double average = personsInAuditorium
.parallelStream()
.filter(p -> p.isStudent())
.mapToInt(Person::getAge)
.average()
.getAsDouble();

Map<Integer, List> groupedByAge =
personsInAuditorium
.parallelStream()
.collect(Collectors.groupingByConcurrent(Person::getAge));

只能是没有顺序的操作才可以parallel stream

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值