把上一篇写的函数式改为for循环,然后打印下线程名
public class Test {
public static void main(String[] args) {
Function<Integer , Integer> fun = x -> {
System.out.println(Thread.currentThread().getName());
return x + 1;
};
for (int i = 0; i < 10; i++) {
Integer integer = TestUtil.execute(i, fun);
System.out.println(integer);
}
}
}
public class TestUtil<T, R> {
private final Function<T, R> mission;
private final T threshold;
public TestUtil(Function<T, R> mission, T threshold) {
this.mission = mission;
this.threshold = threshold;
}
public static <T, R> R execute(T threshold, Function<T, R>mission) {
return new TestUtil<T, R>(mission, threshold).execute();
}
private R execute() {
return mission.apply(threshold);
}
}
跑出来的结果很明显都是主线程
main
1
main
2
main
3
main
4
main
5
main
6
main
7
main
8
main
9
main
10
如果改为多线程的方式
public class Test {
public static void main(String[] args) {
Function<List<Integer>, List<Integer>> fun = x -> {
System.out.println(Thread.currentThread().getName());
return x;
};
for (int i = 0; i < 10; i++) {
List<Integer> id = List.of(i);;
List<Integer> integer = TestUtil.execute(id, fun);
System.out.println("最终"+integer);
}
}
}
public class TestUtil<T, R> {
private final List<T> source;
private final Function<List<T>, List<R>> mission;
public TestUtil(List<T> source,
Function<List<T>, List<R>> mission) {
this.source = source;
this.mission = mission;
}
public static <T, R> List<R> execute(List<T> source, Function<List<T>, List<R>>mission) {
return new TestUtil<T, R>(source, mission).execute();
}
private List<R> execute() {
final List<CompletableFuture<List<R>>> futureList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
futureList.add(CompletableFuture.supplyAsync(() ->mission.apply(source)));
}
/* 聚合所有结果 */
return CompletableFuture.allOf(futureList.toArray(new CompletableFuture[]{}))
.thenApply(v -> futureList.stream().flatMap(data -> {
try {
return data.get().stream();
} catch (Exception e) {
throw new RuntimeException(e);
}
}).collect(Collectors.toUnmodifiableList())).join();
}
}
ForkJoinPool.commonPool-worker-5
ForkJoinPool.commonPool-worker-23
ForkJoinPool.commonPool-worker-19
ForkJoinPool.commonPool-worker-9
ForkJoinPool.commonPool-worker-27
ForkJoinPool.commonPool-worker-5
ForkJoinPool.commonPool-worker-13
ForkJoinPool.commonPool-worker-9
ForkJoinPool.commonPool-worker-19
ForkJoinPool.commonPool-worker-23
最终[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
ForkJoinPool.commonPool-worker-23
ForkJoinPool.commonPool-worker-17
ForkJoinPool.commonPool-worker-23
ForkJoinPool.commonPool-worker-13
ForkJoinPool.commonPool-worker-19
ForkJoinPool.commonPool-worker-27
ForkJoinPool.commonPool-worker-9
ForkJoinPool.commonPool-worker-17
ForkJoinPool.commonPool-worker-5
ForkJoinPool.commonPool-worker-31
最终[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
后面省略
一开始没有对apply进行一个循环,后面发现只有一个线程,初步怀疑是因为只传了一个数进来,线程一下就结束了,所以一直用一个线程。