thenCombine 方法,合并两个线程任务的结果,并进一步处理。有种大数的MapReduce的思想。
@Autowired
@Qualifier(ThreadPoolConfig.IMPORT_EXECUTOR)
private ThreadPoolTaskExecutor threadPoolTaskExecutor;
public List<Object> queryRecentOrders(String custNo) {
CompletableFuture<List<Integer>> future1 = CompletableFuture
.supplyAsync(() -> {
int number = 1;
List<Integer> integers = Lists.newArrayList(number);
System.out.println("first:" + integers);
return integers;
}, threadPoolTaskExecutor);
CompletableFuture<List<Integer>> future2 = CompletableFuture
.supplyAsync(new Supplier<List<Integer>>() {
@Override
public List<Integer> get() {
int number = 2;
List<Integer> integers = Lists.newArrayList(number);
System.out.println("second:" + integers);
return integers;
}
}, threadPoolTaskExecutor);
CompletableFuture<List<Integer>> future3 = CompletableFuture
.supplyAsync(new Supplier<List<Integer>>() {
@Override
public List<Integer> get() {
int number = 3;
List<Integer> integers = Lists.newArrayList(number);
System.out.println("third:" + integers);
return integers;
}
}, threadPoolTaskExecutor);
CompletableFuture<Integer> result = future1
.thenCombine(future2, (x, y) -> {
System.err.println("x:" + x);
System.err.println("y:" + y);
Integer sum = Lists.newArrayList(x, y).stream().flatMap(k -> k.stream()).reduce(0, Integer::sum);
return sum;
}).thenCombine(future3, (x, y) -> {
System.err.println("x:" + x);
System.err.println("y:" + y);
y.add(x);
Integer reduce = y.stream().reduce(0, Integer::sum);
return reduce;
});
try {
Integer integer = result.get();
System.err.println(integer+"-----------------");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
}