异步回调
PPG007 ... 2021-12-28 Less than 1 minute
# 异步回调
public class CompletableFuture<T>
1
# 简单使用
无返回值:
CompletableFuture<Void> completableFuture=CompletableFuture.runAsync(()->{
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
});
completableFuture.get();
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
有返回值:
CompletableFuture<Integer> completableFuture=CompletableFuture.supplyAsync(()->{
int a=10/0;
return 777;
});
System.out.println(completableFuture.whenComplete((integer, throwable) -> {
// 正常结果
System.out.println(integer);
// 错误信息
System.out.println(throwable.getMessage());
}).exceptionally(throwable -> {
System.out.println(throwable.getMessage());
// 出现异常返回值
return 123;
}).get());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15