JUC基础-C7-分支合并框架&异步回调

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();
        
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值