前言
本质其实就是分解和合并
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