1 分支合并框架 Fork/Join
Fork/Join可以将一个大的任务拆分成多个子任务进行并行处理
最后将子任务结果合并成最后的计算结果,并进行输出
Fork: 把一个复杂的任务进行拆分,大事化小
Join: 把分拆任务的结果进行合并
如想要计算1+2+3+...+100这样的操作
可以将其分解为Task1:1+2+...+20 Task2:21+22+40 Task3:...
最后再汇总不同的分支 合并最终结果
使用分支合并框架计算斐波那契数列:
public class Test extends RecursiveTask<Integer> {
private final int n;
public Test(int n) {
this.n = n;
}
@Override
protected Integer compute() {
if(n <= 1) {
return n;
}
// f(n) = f(n-1) + f(n-2)
// 使用fork()打开两个分支分别计算 使用join()合并计算结果
Test t1 = new Test(n - 1);
t1.fork();
Test t2 = new Test(n - 2);
t2.fork();
return t2.join() + t1.join();
}
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
Test test = new Test(4);
ForkJoinPool forkJoinPool = new ForkJoinPool();
ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(test);
int res = forkJoinTask.get();
System.out.println(res);
forkJoinPool.shutdown();
}
2 异步回调 CompletableFuture
同步: 老师去班级中找A同学 发现A同学不在
在班级中什么也不干等待A同学回来
异步: 老师去班级中找A同学 发现A同学不在
告知B同学当A回来后 告诉自己
回到自己的办公室 处理自己的工作直到A同学回来
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 异步调用 无返回值
CompletableFuture<Void> completableFuture1 = CompletableFuture.runAsync(() -> {
System.out.println(Thread.currentThread().getName() + " completableFuture1");
});
completableFuture1.get();
// 异步调用 有返回值
CompletableFuture<Integer> completableFuture2 = CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName() + " completableFuture2");
return 1024;
});
// 当计算完成时返回结果 t为返回值 u为异常信息
completableFuture2.whenComplete((t, u) -> {
System.out.println("t " + t);
System.out.println("u " + u);
}).get();
}
5711

被折叠的 条评论
为什么被折叠?



