编写一个Java函数,通过调用AService.get()、BService.get()、CService.get()三个接口,获取三个整数,然后将这三个整数累加,最终返回累加的值。要求:
1.调用三个接口的操作需要并行执行,以提高效率;
2.累加操作需要在获取三个整数的操作完成后进行,因此需要保证三个整数均已获取后才能进行累加操作;
3.考虑多线程安全问题。
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
public class Test2 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
AService aService = new AService();
BService bService = new BService();
CService cService = new CService();
CompletableFuture<Integer> futureA = CompletableFuture.supplyAsync(() -> aService.get());
CompletableFuture<Integer> futureB = CompletableFuture.supplyAsync(() -> bService.get());
CompletableFuture<Integer> futureC = CompletableFuture.supplyAsync(() -> cService.get());
CompletableFuture<Void> allFutures = CompletableFuture.allOf(futureA, futureB, futureC);
int sum = allFutures.thenApply((v) -> {
int a = futureA.join();
int b = futureB.join();
int c = futureC.join();
return a + b + c;
}).get();
System.out.println("Sum: " + sum);
}
}