package com.model.threadpool;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
/**
* @Description:测试类
* @Author: 张紫韩
* @Crete 2021/6/9 13:50
*/
public class CompletableFutureDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
System.out.println(Thread.currentThread().getName() + "异步开启一个线程,但是没有返回值");
});
completableFuture.get(); //结果,没有返回值的开启另一个线程
//1.异步回调
CompletableFuture<Integer> completableFuture1 = CompletableFuture.supplyAsync(() -> {
//2.子线程执行任务。过一段时间,执行完毕后回将结果返回给主线程
System.out.println(Thread.currentThread().getName() + "异步开启一个线程,有返回值");
// int i=10/0;
return 1024;
});
//3.主线程接受子线程的返回值
Integer integer = completableFuture1.whenComplete((t, u) -> { //接受的返回值
System.out.println(Thread.currentThread().getName() + "返回值:" + t); //返回值正确时,正常返回
System.out.println(Thread.currentThread().getName() + "返回的信息:" + u);
}).exceptionally(f -> {
System.out.println(Thread.currentThread().getName() + "返回的信息:" + f); //返回值出错时,错误信息
return 404;
}).get();
System.out.println(integer);
}
}