import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
//异步调用
public class Demo01 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
/*
//没返回值的异步调用
CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(()->{
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "runAsync");
});
completableFuture.get();
*/
//带返回值的异步调用
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(
()->{
System.out.println(Thread.currentThread().getName() + "supplyAsync,toInt");
int i = 10/0;
return 1024;
}
);
future.whenComplete((t, u)->{
System.out.println("t=" + t);
System.out.println("u=" + u);
}).exceptionally((e)->{e.printStackTrace();
return 233;}).get();
}
}