参考:
https://blog.csdn.net/u012060033/article/details/124469978
https://juejin.cn/post/6993219092375142436
要点:
CompletableFuture是java.util.concurrent库在java 8中新增的用于异步编程的API,同传统的Future相比,其支持流式计算、函数式编程、完成通知、自定义异常处理等很多新的特性。
CompletableFuture表示一个未来完成的任务,支持传入回调函数在任务执行完成后执行回调函数。
实现接口:
public class CompletableFuture<T> implements Future<T>, CompletionStage<T>
Future表示异步计算的结果,提供了检查任务是否完成、等待任务完成以及获取任务结果的方法。
CompletionStage是Java 8 新增的接口,表示执行任务的阶段,提供在任务执行阶段中执行某种操作的能力。
例子代码:
public static void testVoid(){
CompletableFuture<Void> future = CompletableFuture.runAsync(new Runnable() {
@Override
public void run() {
System.out.println("start");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("end");
}
});
System.out.println("main");
try {
future.get();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
public static void testInteger(){
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {
@Override
public Integer get() {
System.out.println("start");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("end");
return 123456;
}
});
System.out.println("main");
try {
Integer integer = future.get();
System.out.println("value=" + integer);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}