JUC(一)异步调用CompletableFuture
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());
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();