Callable与Future
2016-12-30 17:03
113 查看
Callable与Future
使用线程池来创建并行的任务:
这个一个简单的demo,可以在最后统一获取执行结果;以此类推
方案一:
企业应用:
使用线程池来创建并行的任务:
这个一个简单的demo,可以在最后统一获取执行结果;以此类推
方案一:
ExecutorService threadPool = Executors.newFixedThreadPool(2); Future<Integer> future = threadPool.submit(new Callable<Integer>() { public Integer call() throws Exception { return 1; } }); Future<Integer> futureNew = threadPool.submit(new Callable<Integer>() { public Integer call() throws Exception { return 2; } }); try { System.out.println(future.get()); System.out.println(futureNew.get()); } catch (Exception e) { e.printStackTrace(); }
企业应用:
public static void main(String[] args) throws ParseException { try{ ThreadPoolExecutor threadPool = ImportDataThreadPoolUtil.getInstance(); FutureTask<Boolean> futureTask = new FutureTask(new Callable() { public Boolean call() throws Exception { //do something return null; } }); threadPool.execute(futureTask); Boolean flag = false; Long userTime = 0L; while (userTime < 10) { flag = futureTask.get(); if (futureTask.isDone() ) { break; } Thread.sleep(500);//线程锁定 userTime++; } }catch (Exception e){ System.out.println("error ~~"); } }
相关文章推荐
- linux常用的快捷键
- 使用SQL Server连接服务器访问DB2 Server
- Visual Studio开发工具集和Eclipse JAVA集成开发环境
- 内置过滤器
- Python学习笔记
- 《实时控制软件》第四周作业
- HDU1115--Lifting the Stone(求凸多边形的重心)
- C# ShellExcute与Process
- C# 系统托盘图标
- dubbo学习-2-配置
- Non-Obvious Debugging Techniques
- 在一个千万级的数据库查寻中,如何提高查询效率?
- __STDC_CONSTANT_MACROS和__STDC_CONSTANT_MACROS的作用
- Qt常用类QAction类及方法简介
- QQ图片分享和网页分享
- 基于pxe+cobbler的全自动化安装centos系统
- ScrollView简单定制
- ffmpeg常用命令
- Caffe学习(2) Windows 版本 运行mnist数据集
- 检查输入的字符是否为合法变量名(迭代)