Java异步调用Future对象
Future类存在于JDK的concurrent包中,主要用途是接收Java的异步线程计算返回的结果。
个人理解的使用场景大概如下:
有两个任务A和B,A任务中仅仅需要使用B任务计算成果,有两种方法实现:
- A和B在同一个线程中顺序执行。即先执行B,得到返回结果之后再执行A。
- 开两个线程,A和B并行执行。当A需要B的计算结果时如果B还没有执行完,A既可以选择阻塞等待B执行完,也可以先做其他的工作,过一段时间后再询问一次B。
毫无疑问,如果B是一个耗时比较大的计算任务时,后者比前者的效率高了很多。
使用Java的Future对象的实现。
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future; public class FutureDemo { public static void main(String[] args) { ExecutorService threadPool = Executors.newCachedThreadPool();
Future<Integer> future = threadPool.submit(new Callable<Integer>() {
public Integer call() throws Exception {
Thread.sleep(3000);
return new Random().nextInt(100);
}
}); doSomething(); try {
System.out.println("is B done : " + future.isDone());
System.out.println("result of B : " + future.get());
System.out.println("is B done : " + future.isDone());
int result = future.get(); doSomethingWithB(result);
}
catch (InterruptedException e) {
e.printStackTrace();
}
catch (ExecutionException e) {
e.printStackTrace();
}
System.exit(0);
} private static void doSomethingWithB(int result) {
// TODO Auto-generated method stub } private static void doSomething() {
// TODO Auto-generated method stub } }
输出结果:
is B done : false
result of B : 25
is B done : true
Future对象使用get方法获取线程的返回值,即call方法的返回值。
不带参数的get方法是阻塞方法,只要线程为返回结果就会一直阻塞直到有结果为止。
可以使用isDone方法判断线程是否结束。也可以使用带参数的get方法,若指定时间内还没有得到线程返回值,会抛出TimeoutException的异常。
该方法源码:
/**
* Waits if necessary for at most the given time for the computation
* to complete, and then retrieves its result, if available.
*
* @param timeout the maximum time to wait
* @param unit the time unit of the timeout argument
* @return the computed result
* @throws CancellationException if the computation was cancelled
* @throws ExecutionException if the computation threw an
* exception
* @throws InterruptedException if the current thread was interrupted
* while waiting
* @throws TimeoutException if the wait timed out
*/
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
Java异步调用Future对象的更多相关文章
- 说说Java异步调用的几种方式
日常开发中,会经常遇到说,前台调服务,然后触发一个比较耗时的异步服务,且不用等异步任务的处理结果就对原服务进行返回.这里就涉及的Java异步调用的一个知识.下面本文尝试将Java异步调用的多种方式进行 ...
- 5种必会的Java异步调用转同步的方法你会几种
转载请注明本文地址:https://www.jianshu.com/p/f00aa6f66281 源码地址:https://gitee.com/sunnymore/asyncToSync Sunny先 ...
- Java异步调用转同步的5种方式
1.异步和同步的概念 同步调用:调用方在调用过程中,持续等待返回结果. 异步调用:调用方在调用过程中,不直接等待返回结果,而是执行其他任务,结果返回形式通常为回调函数. 2 .异步转为同步的概率 需要 ...
- java异步调用方法
一.利用多线程 直接new线程 Thread t = new Thread(){ @Override public void run() { longTimeMethod(); } }; 使用线程池 ...
- java异步计算Future的使用(转)
从jdk1.5开始我们可以利用Future来跟踪异步计算的结果.在此之前主线程要想获得工作线程(异步计算线程)的结果是比较麻烦的事情,需要我们进行特殊的程序结构设计,比较繁琐而且容易出错.有了Futu ...
- Dubbo消费者异步调用Future使用
Dubbo的四大组件工作原理图,其中消费者调用提供者采用的是同步调用方式.消费者对于提供者的调用,也可以采用异步方式进行调用.异步调用一般应用于提供者提供的是耗时性IO服务 一.Future异步执行原 ...
- java 异步调用与多线程
异步与多线程的区别 一.异步和多线程有什么区别?其实,异步是目的,而多 线程是实现这个目的的方法.异步是说,A发起一个操作后(一般都是比较耗时的操作,如果不耗时的操作 就没有必要异步了),可以继续自顾 ...
- java反射调用某个对象的方法
// 反射调用某个对象的方法 public Object invokeMethod(Object methodObject, String methodName, Object[] args) thr ...
- 从Java future 到 Guava ListenableFuture实现异步调用
从Java future 到 Guava ListenableFuture实现异步调用 置顶 2016年04月24日 09:11:14 皮斯特劳沃 阅读数:17570 标签: java异步调用线程非阻 ...
随机推荐
- poj 2976 Dropping tests (二分搜索之最大化平均值之01分数规划)
Description In a certain course, you take n tests. If you get ai out of bi questions correct on test ...
- User Defined Runtime Attributes
设置View borderWidth/cornerRadius/borderColor 为了兼容CALayer 的KVC ,你得给CALayer增加一个分类 CALayer+BorderColor.h ...
- [转] ubuntu 一些常用软件的安装
首先说明一下 ubuntu 的软件安装大概有几种方式: 1. deb 包的安装方式deb 是 debian 系 Linux 的包管理方式, ubuntu 是属于 debian 系的 Linux 发行版 ...
- Java第四周学习日记(绪)
1.静态导入 作用:简化书写静态导入可以作用一个类的所有静态成员静态导入格式:import static 包名.类名静态导入要注意的事项:如果静态导入的成员与本类的成员存在同名的情况下,那么默认使用本 ...
- 支持多QQ登录的软件
支持多QQ登录,批量加好友,批量回复QQ消息,当然也能接收 下载链接:多QQ登录软件
- C#基础:C#4.0权威指南 杂笔一
1.c#中数组初始化的几种不同用法 int[] name = new int[NUM]; int[] name = {1, 2, 3, 4, 5, 6}; int[] ...
- OWIN启动项的检测
OWIN启动项的检测 通过以下方法设置启动项: 命名约定 Katana在命名空间内查找StartUp类 OwinStartup Attribute [assembly: OwinStartup(typ ...
- 再关于IE11
微软在上周刚刚发布了用于Windows 8.1上的首个Internet Explorer 11的预览版.我们已经确认Internet Explorer 11中的一些新特性,包括对WebGL的支持.预抓 ...
- Jquery:强大的选择器<二>
今天跟着资料做了一个示例,为什么我感觉自己做的没书上的好看呢?好吧,我承认自己对css样式只懂一点皮毛,我也不准备深度的去学习它,因为……公司有美工嘛! 这个小示例只是实现了元素的隐藏和显示.元素cl ...
- SDOI HH的项链 HEOI采花
题目大意: SDOI求一个区间内只出现一次的数的个数.多组询问. HEOI 求一个区间内出现至少两次的数的个数.多组询问. SDOI HH'neckplace如果每次询问都是1..r的话,那么我们只要 ...