异步回调
Future 设计的初衷:对未来的结果建模
package com.example.juc;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class TestAsync {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 无返回值的异步回调
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "Thread-> void");
});
System.out.println(1111); // 1111
future.get(); // 等待2s ForkJoinPool.commonPool-worker-9Thread-> void
// 有返回值的异步回调
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "Thread-> Integer");
int i = 10 / 0;
return 1;
});
System.out.println(future1.whenComplete((u, t) -> {
System.out.println("u->" + u);
System.out.println("t->" + t);
}).exceptionally((e) -> {
System.out.println(e.getMessage());
return 2;
}).get());
}
}
1111
ForkJoinPool.commonPool-worker-9Thread-> void
ForkJoinPool.commonPool-worker-9Thread-> Integer
u->null
t->java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero
java.lang.ArithmeticException: / by zero
2