Callable方法比Runnable强大一些在于它被线程执行后有返回值,该返回值可以被Future拿到。
用法:
Callable<Integer> callable = new Callable<Integer>(){
public Integer call() throws Exception {
//do sth
}
};
FutureTask<Integer> future = new FutureTask<Integer>(callable);
new Thread(future).start();
String result = future.get();//获取返回结果
下面看另一种方式使用Callable和Future,通过ExecutorService的submit方法执行Callable,并且返回Future:
ExecutorService threadPool = Executors.newSingleThreadExecutor();
Future<Integer> future = threadPool.summit(new Callable<Integer>(){
public Integer call() throws Exception {
//do sth
}
});
future.get();
执行多个待返回值得任务,并取得多个返回值:
ExecutorService threadPool = Executors.newCachedThreadPool();
CompletionService<Integer> cs = new ExecutorCompletionService<Integer>(threadPool);
for (int i = 1 ; i < 5 ; i++) {
final int taskID = i;
cs.submit(new Callable<Integer>(){
public Integer call() throws Exception{
return taskID;
}
};
}
for(int i = 1 ; i < 5 ; i++) {
cs.take().get
}
其实也可以不使用CompletionService,可以先创建一个装Future类型的集合,用Executor提交的任务返回值添加到集合中,最后遍历集合取出数据。
原文地址:http://6169621.blog.51cto.com/6159621/1570757