1. 有返回值的异步调用CompletableFuture.supplyAsync()
1. 代码示例
//有返回值的异步调用
CompletableFuture<Integer> completableFutureSupply = CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName() + " supplyAsync => Integer");
int i = 10/1;
return 1024;
});
2.获取返回值
System.out.println(completableFutureSupply.get());
//输出结果-> 1024
3.异步方法中报错处理
1.写个异常(被除数为整型时不可为零)
//有返回值的异步调用
CompletableFuture<Integer> completableFutureSupply = CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName() + " supplyAsync => Integer");
int i = 10/0;
return 1024;
});
2. 使用whenComplete解决异常后返回值的问题
System.out.println(completableFutureSupply.whenComplete((t, u) -> {
System.out.println("t=" + t);
System.out.println("u=" + u);
}).exceptionally((e) -> {
System.out.println("ex:"+e.getMessage());
return 233;
}).get());
- 这里代码依旧还是出现异常,但是我们在异常代码块中给他定义了一个报错还可以正常返回的默认值
- t =正常返回值
- u=异常信息
- e=异常信息
1.无异常情况,我这边将被除数改回非0
2.异步调用CompletableFuture.runAsync()
CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " runAsync => Void");
});
completableFuture.get();//阻塞获取执行结果
//批量阻塞(等待)
CompletableFuture.allOf(completableFuture,completableFuture1).join();