CompletableFuture是干啥的,此处不再赘述,网上资料很多。我就拿一个简单的应用来直观的说明它的作用。
应用场景:把一个串行操作优化为并行操作。减少程序执行的时间开销。
此处有三个操作,fun1、fun2、fun3,代码如下
private static String fun1() {
try {
sleep(2000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "fun1";
}
private static String fun2() {
try {
sleep(3000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "fun2";
}
private static String fun3() {
try {
sleep(3000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "fun3";
}
按照我们正常的执行逻辑,也就是串行执行,很明显,肯定是大于8s的。代码如下
private static void test() {
long startTime = System.currentTimeMillis();
String s1 = fun1();
String s2 = fun2();
String s3 = fun3();
System.out.println(Thread.currentThread().getName() + "线程耗时:" + (System.currentTimeMillis() - startTime));
System.out.println(s1 + s2 + s3);
}
运行结果
main线程耗时:8002
fun1fun2fun3
现在,我们通过CompletableFuture进行优化,改为并行执行,代码如下
private static void testCompletableFuture() {
long startTime = System.currentTimeMillis();
CompletableFuture cf1 = CompletableFuture.supplyAsync(MyCompleteFuture::fun1);
CompletableFuture cf2 = CompletableFuture.supplyAsync(MyCompleteFuture::fun2);
CompletableFuture cf3 = CompletableFuture.supplyAsync(MyCompleteFuture::fun3);
String result = (String) cf1.thenCombine(cf2, (s1, s2) -> s1 + "" + s2).thenCombine(cf3, (s1, s2) -> s1 + "" + s2).join();
System.out.println(Thread.currentThread().getName()+"线程耗时:"+(System.currentTimeMillis() - startTime));
System.out.println(result);
}
运行结果
main线程耗时:3079
fun1fun2fun3
通过执行时间,由8s缩短为3s。这个提升是很明显的。
总结一下,有如下几点:
1.CompletableFuture是java8提供的支持并发编程的一个异步非阻塞的功能。通过它,可以优雅的获取异步执行的结果,也可以合并多个异步执行的结果。而不像Future那样,必须要阻塞的获取结果。
2.CompletableFuture封装很多并发编程的技术,降低了并发编程的门槛。
3.结合函数式编程,使并发编程的代码更加优雅,简洁。