Future的使用
来源:互联网 发布:数据电视怎么调画面 编辑:程序博客网 时间:2024/05/20 06:26
ExecutorService的使用:
List<Future<List<VO>>> futureList = new ArrayList<Future<List<VO>>>();
//用Executors创建一个ExecutorService
ExecutorService executorService = Executors.newCachedThreadPool();
try {
for (T t : list)
//发起一个线程
Future<List<VO>> f = executorService.submit(new QueryTask(t));
futureList.add(f);
}
//Future类会等待线程执行完毕,再做操作
for (Future<List<VO>> future : futureList) {
try {
rows.addAll(future.get());
}catch (Exception e) {
throw new RuntimeException("查询任务线程异常");
}
}
} finally {
//关闭线程服务
executorService.shutdown();
}
/**
* 异步查询任务
*/
private class QueryTask implements Callable<List<VO>> {
private T t;
QueryTask(T t) {
this.t = t;
}
/**
* @see java.util.concurrent.Callable#call()
*/
@Override
public List<VO> call() throws Exception {
//具体的执行方法
return method(this.t);
}
}
ExecutorService的使用场景:可以在页面查询的时候使用,比如查询多个接口,可以起多个线程,最后合并结果,可以节约时间,防止请求超时。虽然可以在代码中设置线程池参数,这样就不利于维护。
List<Future<List<VO>>> futureList = new ArrayList<Future<List<VO>>>();
//用Executors创建一个ExecutorService
ExecutorService executorService = Executors.newCachedThreadPool();
try {
for (T t : list)
//发起一个线程
Future<List<VO>> f = executorService.submit(new QueryTask(t));
futureList.add(f);
}
//Future类会等待线程执行完毕,再做操作
for (Future<List<VO>> future : futureList) {
try {
rows.addAll(future.get());
}catch (Exception e) {
throw new RuntimeException("查询任务线程异常");
}
}
} finally {
//关闭线程服务
executorService.shutdown();
}
/**
* 异步查询任务
*/
private class QueryTask implements Callable<List<VO>> {
private T t;
QueryTask(T t) {
this.t = t;
}
/**
* @see java.util.concurrent.Callable#call()
*/
@Override
public List<VO> call() throws Exception {
//具体的执行方法
return method(this.t);
}
}
ExecutorService的使用场景:可以在页面查询的时候使用,比如查询多个接口,可以起多个线程,最后合并结果,可以节约时间,防止请求超时。虽然可以在代码中设置线程池参数,这样就不利于维护。
阅读全文
0 0
- callable&future的使用
- Future的使用
- Future的使用
- Future的使用
- java Future的使用
- Future和FutureTask的使用
- Callable&&Future的基本使用
- Java多线程Future的使用
- 巩固 Java Future 的使用
- Callable和future的使用
- C++Future简单的使用
- 多线下,CountDownLatch,Future的使用
- twitter的Future的简单使用
- Future接口和Callable接口的使用
- java异步计算Future的使用
- Future的使用,不是应用哦
- java异步计算Future的使用
- java异步计算Future的使用
- spring4.0整合了validation验证功能
- HTML CSS JS 思维导图
- leetcode78 subset
- rabbmitmq安装笔记
- linux tar.gz zip 解压缩 压缩命令
- Future的使用
- 09、vue.js 之自定义指令
- HashMap要点记
- java.lang.IllegalArgumentException: Scrapped or attached views may not be recycled. isScrap:false is
- 数据库事务隔离级别-- 脏读、幻读、不可重复读(清晰解释)
- JUnit自动化单元测试(五):参数化测试
- 菜鸟重新了解C#
- HDU
- [Linux]history命令用法详解