编写一个Java函数,通过调用AService.get()、BService.get()、CService.get()三个接口,获取三个整数,然后将这三个整数累加,最终返回累加的值

public class Aservice {

    public static Integer get(){
       System.out.println("A被调用了");
        return 10;
    }
}
public class BService {

    public static Integer get(){
        System.out.println("B被调用了");
        return 20;
    }

}
public class CService {

    public static Integer get(){
        System.out.println("C被调用了");
        return 30;
    }
}
package com.company;


import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 第二题
 * 编写一个Java函数,通过调用AService.get()、BService.get()、CService.get()三个接口,获取三个整数,然后将这三个整数累加,最终返回累加的值。要求:
 * 1.调用三个接口的操作需要并行执行,以提高效率;
 * 2.累加操作需要在获取三个整数的操作完成后进行,因此需要保证三个整数均已获取后才能进行累加操作;
 * 3.考虑多线程安全问题。
 */
public class Test {

    public static void main(String[] args) {
       Test test=new Test();
       System.out.println(test.get());

    }

    public Integer get(){
        //初始值为0 为了保证多线程情况下的累加原子性 就是保证数据不累加错误
        //使用AtomicInteger
        AtomicInteger sum=new AtomicInteger(0);
        //并发调用三个接口
        CompletableFuture<Integer> a=CompletableFuture.supplyAsync(()->Aservice.get());
        CompletableFuture<Integer> b=CompletableFuture.supplyAsync(()->BService.get());
        CompletableFuture<Integer> c=CompletableFuture.supplyAsync(()->CService.get());
        //阻塞3个线程 执行完毕才往下走  join()是阻塞
        CompletableFuture.allOf(a,b,c).join();
        //把3个线程的结果 加起来
        a.thenAccept(x->sum.addAndGet(x));
        b.thenAccept(x->sum.addAndGet(x));
        c.thenAccept(x->sum.addAndGet(x));
        //最后返回累加的结果
        return sum.get();
    }


}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值