没有返回值的异步回调(runAsync):
public class TestFuture {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//发起一个异步请求(没有返回值)
CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(()->{
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"runAsync=>Void");
});
System.out.println("main线程");
completableFuture.get();//获取阻塞执行结果
}
}
结果:
main线程
ForkJoinPool.commonPool-worker-1runAsync=>Void
有返回值的异步回调(supplyAsync):
返回成功:
public class TestFuture {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//有返回值的异步回调(supplyAsync)
//有成功和失败的回调
CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName()+"supplyAsync=>Integer");
return 1024;
});
completableFuture.whenComplete((t,u)->{ //执行成功
System.out.println("t->"+t);//正常的返回结果
System.out.println("u->"+u);
}).exceptionally((e)->{ //执行失败
System.out.println(e.getMessage());
return 203;
}).get();
}
}
结果:
ForkJoinPool.commonPool-worker-1supplyAsync=>Integer
t->1024
u->null
返回失败:
public class TestFuture {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//有返回值的异步回调(supplyAsync)
//有成功和失败的回调
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);//返回的错误的信息:java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero
}).exceptionally((e) -> {
System.out.println(e.getMessage());
return 203;
}).get());
}
}
结果:
ForkJoinPool.commonPool-worker-1supplyAsync=>Integer
t->null
u->java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero
java.lang.ArithmeticException: / by zero
203
网友评论