Version: Next

异步回调

Future接口设计的初衷:对将来的某个时间的结果进行建模

  • 实现类:CompleteableFuture<T>
    • 异步执行
    • 成功回调
    • 失败回调
  • CompleteableFuture.runAsync(Runnable runnable)
  • CompleteableFuture.runAsync(Runnable runnable, Executor, executor)

类似Ajax

  • 无返回值——runAsync
@Test
public void test() throws ExecutionException, InterruptedException {
CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
try {
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName() + "runAsync");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println("1111");
//获取执行结果
completableFuture.get();
}
1111
ForkJoinPool.commonPool-worker-1runAsync

  • 有返回值的情况——supplyAsync
    • whenComplete(BiConsumer)——双参数的消费型接口
@Test
public void test2() throws ExecutionException, InterruptedException {
CompletableFuture<Integer> completableFuture =
CompletableFuture.supplyAsync(() -> 1024);
completableFuture
.whenComplete((t, u) ->
// t 是正常返回的结果
System.out.println("t : " + t + " | u : " + u))
.exceptionally(e -> {
System.out.println(e.getMessage());
return 233;
}).get();
}
t : 1024 | u : null

人为制造一个异常

@Test
public void test2() throws ExecutionException, InterruptedException {
CompletableFuture<Integer> completableFuture =
CompletableFuture.supplyAsync(() -> {
int i = 10 / 0;
return 1024;
});
completableFuture
.whenComplete((t, u) ->
// u 是异常返回的结果
System.out.println("t : " + t + " | u : " + u))
.exceptionally(e -> {
System.out.println(e.getMessage());
return 233;
}).get();
}
t : null | u : java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero
java.lang.ArithmeticException: / by zero