Future是java 1.5引入的一个interface,可以方便的用于异步结果的获取。
Future代表的是异步执行的结果,意思是当异步执行结束之后,返回的结果将会保存在Future中。(可以对比ajax异步调用进行学习)
那么我们什么时候会用到Future呢? 一般来说,当我们执行一个长时间运行的任务时,使用Future就可以让我们暂时去处理其他的任务,等长任务执行完毕再返回其结果。
示例:无参的异步调用
public class FutureDemo {
/**
* 异步调用
* 1. 异步执行
* 2. 成功回调
* 3. 失败回调
*/
public static void main(String[] args) throws ExecutionException, InterruptedException {
//发起一个请求 没有返回值
CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(()->{
try {
//休眠两秒
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"runAsync--->void");
});
System.out.println("11111");
//获取执行结果 会阻塞等待获取这个结果
completableFuture.get();
System.out.println("22222");
}
}
//结果
11111
ForkJoinPool.commonPool-worker-1runAsync--->void
22222
//将睡眠去掉结果也是一样的
示例 :有参的异步调用
public class FutureDemo {
/**
* 异步调用
* 1. 异步执行
* 2. 成功回调
* 3. 失败回调
*/
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(()->{
System.out.println(Thread.currentThread().getName());
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 1024;
});
System.out.println(completableFuture.whenComplete((t,u)->{
//success 回调
System.out.println("t=>" +t);//正常的返回结果
System.out.println("u=>" +u);//抛出异常的错误信息
//int a=1/0;
}).exceptionally((e)->{
//error 回调
System.out.println(e.getMessage());
return 404;
}).get());
}
}
结果
ForkJoinPool.commonPool-worker-1
t=>1024
u=>null
1024
//将//int a=1/0;的注释去掉,运行结果如下
ForkJoinPool.commonPool-worker-1
t=>1024
u=>null
java.lang.ArithmeticException: / by zero
404