随着java8的到来,一大批好用的操作也来到我们的身边。
我们今天先来小尝一下CompletableFuture
这个类是Future的实现类,同时实现了一大堆别的接口。
粗粗一数,大概有50多个方法,深入的东西小伙伴们自己去研究吧,我带大家先来一发初体验。
package playground; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ForkJoinPool; /** * Created by tarner on 17/9/15. */ public class Play { public static void main(String[] args) throws Exception { long currentTimeMillis = System.currentTimeMillis(); CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(() -> fun1()); CompletableFuture.runAsync(new A(f1)); CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(() -> fun2()); CompletableFuture.runAsync(new A(f2)); ForkJoinPool forkJoinPool = ForkJoinPool.commonPool(); while (!forkJoinPool.isQuiescent()) { } System.out.println("耗时" + (System.currentTimeMillis() - currentTimeMillis)); } private static int fun1() { System.out.println("fun1 bejin"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("fun1 end"); return 1; } private static int fun2() { System.out.println("fun2 bejin"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("fun2 end"); return 2; } }
package playground; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; /** * Created by tarner on 17/9/15. */ public class A implements Runnable { private CompletableFuture f; public A(CompletableFuture f) { this.f = f; } @Override public void run() { try { System.out.println(f.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }
结果
fun1 bejin
fun2 bejin
fun1 end
fun2 end
2
1
耗时2194
解读
A类实现了Runable接口,其中之有一个操作,就是调用CompletableFuture的get方法。
主函数中fun1方法,fun2方法都是人为制造的需要sleep2秒的方法,我们在这里模拟那些需要花时间才能知道结果的方法。
CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(() -> fun1()); CompletableFuture.runAsync(new A(f1)); CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(() -> fun2()); CompletableFuture.runAsync(new A(f2));
重点来了
supplyAsync接受一个有返回结果的function(fun1)
runAsync接受一个实现Runable的对象(A)。
我们A的构造方法需要一个CompletableFuture(f1)
我们可以看到整个方法走下来用了2194毫秒
fun1(),fun2()都是需要2000毫秒的
如果是同步方式,一定要4000毫秒+才能执行完。
CompletableFuture帮助我们更好的写并发程序,提高并发量。