开发中,我们有时会遇到这样的需求,某个接口需要的数据需要从各个不同的表中去查询,最后把结果组装到一起,这些操作可能是没有关联的,也有可能是互相依赖的,比如B语句需要A语句的查询结果作为入参再去查询,这个时候,我们使用CompletableFuture这个类,就可以很方便的解决这些场景,并且极大的提升效率。
//加法
public static Integer jiafa(Integer a, Integer b) {
ThreadUtil.sleep(1000);
Integer res = a + b;
return res;
}
//乘法
public static Integer chengfa(Integer a, Integer b) {
ThreadUtil.sleep(2000);
Integer res = a * b;
return res;
}
//除法
public static Integer chufa(Integer a, Integer b) {
ThreadUtil.sleep(3000);
Integer res = a / b;
return res;
}
这是三个方法,耗时分别为1,2,3秒,正常调用这三个方法,耗时应该是1+2+3,六秒多。
public static void main(String[] args) {
System.out.println("main==============start");
long l = System.currentTimeMillis();
chengfa(2,3);
jiafa(5,5);
chufa(20,5);
long l1 = System.currentTimeMillis();
System.out.println("main==============end,耗时:" + (l1 - l));
}
可以看到,总耗时为六秒多一点,效率很低。
下面使用CompletableFuture简单改一下代码:
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("main==============start");
long l = System.currentTimeMillis();
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
Integer chengfa = chengfa(2, 3);
return chengfa;
});
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
Integer jiafa = jiafa(5, 5);
return jiafa;
});
CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> {
Integer chufa = chufa(15, 5);
return chufa;
});
CompletableFuture<Void> res = CompletableFuture.allOf(future1, future2, future3);
res.get();
System.out.println("future1结果:"+future1.get()+"===future2结果:"+future2.get()+"===future3结果:"+future3.get());
long l1 = System.currentTimeMillis();
System.out.println("main==============end,耗时:" + (l1 - l));
}
可以看到,耗时变成了三秒多一点,也就是三个异步任务中耗时最长的任务的时间多一点,提升了效率。
上面是一个非常简单的列子,CompletableFuture类中还提供了很多api可以让我们非常简单的对异步任务进行编排,在需要的时候去查阅即可。