异步回调
Future 接口在 Java 5 中被引入,设计初衷是对将来某个时刻会发生的结果进行建模。
它建模了一种异步计算,返回一个执行运算结果的引用,当运算结束后,这个引用被返回
给调用方。在Future中触发那些潜在耗时的操作把调用线程解放出来,让它能继续执行其
他有价值的工作,不需要等待耗时的操作完成。
没有返回值的runAsync 异步回调
public static void main(String[] args) {
CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "runAsync");
});
System.out.println("1111");
try {
completableFuture.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
有返回值的supplyAsync 异步回调 ,有成功
@Test
public void test() {
CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "runAsync");
return 1024;
});
System.out.println("1111");
try {
completableFuture.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
有返回值的supplyAsync 异步回调 ,有成功和失败
@Test
public void test2() throws InterruptedException, ExecutionException {
CompletableFuture<Integer> completableFuture =
CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName() + "supplyAsync=>Integer");
int i = 10 / 0;
return 1024;
});
System.out.println(completableFuture.whenComplete((t, u) -> {
System.out.println("t=>" + t);
System.out.println("u=>" + u);
}).exceptionally((e) -> {
System.out.println(e.getMessage());
return 233;
}).get());
}