异步回调–对比Ajax
runAsync 没有返回值的异步调用
正常执行测试:
public class FutureAsync {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//没有返回值的异步调用 runAsync
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("1111");
completableFuture.get();//获取阻塞执行的结果
}
}
执行结果:
1111
ForkJoinPool.commonPool-worker-1runAsync=>void
null
执行出现异常测试:
public class FutureAsync {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//没有返回值的异步调用 runAsync
CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(()->{
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
int i=1/0;
System.out.println(Thread.currentThread().getName()+"runAsync=>void");
});
System.out.println("1111");
completableFuture.get();//获取阻塞执行的结果
}
}
执行结果:
1111
Exception in thread "main" java.util.concurrent.ExecutionException: java.lang.ArithmeticException: / by zero
supplyAsync 有返回值的异步调用
正常执行测试:
public class FutureAsync {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//有返回值的异步调用 supplyAsync
CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(()->{
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"supplyAsync=>Integer");
return 1024;
});
System.out.println("aaaaaaa");
Integer integer = completableFuture.whenComplete((t, u) -> {//t u只有一个会有数据
System.out.println("t=>" + t);//t 正常执行的返回值,这里指的是return 1024
System.out.println("u=>" + u);//u 执行报错时的错误信息
}).exceptionally((e) -> {
System.out.println("e=>"+e.getMessage());
return 404;//执行报错时会获得错误的返回结果
}).get();
System.out.println(integer);
}
}
执行结果:
aaaaaaa
ForkJoinPool.commonPool-worker-1supplyAsync=>Integer
t=>1024
u=>null
1024
执行出现异常测试:
public class FutureAsync {
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 = 1/0;
return 1024;
});
Integer integer = completableFuture.whenComplete((t, u) -> {//t u只有一个会有数据
System.out.println("t=>" + t);//t 正常执行的返回值,这里指的是return 1024
System.out.println("u=>" + u);//u 执行报错时的错误信息
}).exceptionally((e) -> {
System.out.println("e=>"+e.getMessage());
return 404;//执行报错时会获得错误的返回结果
}).get();
System.out.println(integer);
}
}
执行结果:
ForkJoinPool.commonPool-worker-1supplyAsync=>Integer
t=>null
u=>java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero
e=>java.lang.ArithmeticException: / by zero
404