您的位置:首页 > 其它

Callable与Future

2016-12-30 17:03 113 查看
Callable与Future

使用线程池来创建并行的任务:

这个一个简单的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 ~~");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: