Java8新特性之CompletableFuture详解

jdk1.8中加入了CompletableFuture类来辅助实现异步编程。上一节中提到了线程池执行异步方法返回Fufure实例,但是当执行多个异步任务时,如何判断这些任务都已执行完毕则没有好的办法,只能通过定时轮询去判断这些任务isDone(),并且也需要创建线程池来实现。而新的CompletableFufure类则对异步编程提供了一些很不错的方法。如下:

静态方法:
CompletableFuture.runAsync(Runnable r);执行无返回值得异步接口,返回CompletableFufure对象,get()方法是阻塞的。

CompletableFufure.supplyAsync(Supplier s);执行异步有返回值的方法,

CompletableFufure.allof(CompletableFufure...c) 一组异步方法都执行成功时返回CompletableFuture方法。

CompletableFufure.anyOf( CompletableFufure...c )一组异步方法,有一个执行成功时就返回。

实例方法:
thenAccept(Consumer c)执行成功之后执行的方法

thenApply(Function f )执行成功之后执行有参数的方法

thenCompose(T t,Function f )执行成功后携带参数执行方法

thenCombine()与第二个异步方法合并,都执行成功后执行其他
参考代码:
package com.example.thread;


import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFutureTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
Long start = System.currentTimeMillis();
CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return new Random().nextInt(10);
});
CompletableFuture completableFuture1 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 3;
});
CompletableFuture completableFuture2 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 5;
});
System.out.println("start");
CompletableFuture anyOf = CompletableFuture.anyOf(completableFuture, completableFuture1, completableFuture2);
System.out.println(anyOf.get());
System.out.println("execute time:" + (System.currentTimeMillis() - start));
System.out.println(completableFuture.isDone());
System.out.println(completableFuture1.isDone());
System.out.println(completableFuture2.isDone());
CompletableFuture allOf = CompletableFuture.allOf(completableFuture, completableFuture1, completableFuture2);
CompletableFuture completableFuture3 = CompletableFuture.runAsync(new Runnable() {
@Override
public void run() {
System.out.println("runAsync");
}
});
System.out.println(allOf.get());
System.out.println("execute time:" + (System.currentTimeMillis() - start));
System.out.println(completableFuture.isDone());
System.out.println(completableFuture1.isDone());
System.out.println(completableFuture2.isDone());
//
Integer s = completableFuture2.thenCompose(resInt -> CompletableFuture.supplyAsync(() -> resInt + 123)).get();
Integer s2 = completableFuture1.thenCombine(completableFuture2, (int1, int2) -> int1 + int2).get();
System.out.println(s2);
System.out.println(s);
}
}




你可能感兴趣的:(项目实战)