本节主要讲下 Callable和Future 的使用它俩很有意思的,一个产生结果,一个拿到结果。 Callable接口类似于Runnable,从名字就可以看出来了,但是Runnable不会返回结果,并且无法抛出返回结果的异常,而Callable功能更强大一些,被线程执行后,可以返回值,这个返回值可以被Future拿到,也就是说,Future可以拿到异步执行任务的返回值,下面来看一个简单的例子:
public class CallableAndFuture {
public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
ExecutorService threadPool= Executors.newSingleThreadExecutor();
Future future= threadPool.submit(new Callable<String>(){
public String call() throws Exception {
Thread.sleep(2000);
return "hello";
}
});
System.out.println("等待结果");
System.out.println("结果"+future.get());
}
}
FutureTask实现了两个接口,Runnable和Future,所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值,那么这个组合的使用有什么好处呢?假设有一个很耗时的返回值需要计算,并且这个返回值不是立刻需要的话,那么就可以使用这个组合,用另一个线程去计算返回值,而当前线程在使用这个返回值之前可以做其它的操作,等到需要这个返回值时,再通过Future得到
public class FutureTaskTest {
public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
Callable<Integer> callable = new Callable<Integer>() {
public Integer call() throws Exception {
int task=new Random().nextInt(5000);
Thread.sleep(task);
return task;
}
};
FutureTask<Integer> future = new FutureTask<Integer>(callable);
new Thread(future).start();
try {
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
可以使用CompletionService去提交一组任务
public class CallableAndCompletion {
public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
ExecutorService threadPool= Executors.newFixedThreadPool(10);
CompletionService<Integer> com=new ExecutorCompletionService<Integer>(threadPool);
for (int i=1;i<=10;i++){
final int task=i;
com.submit(new Callable<Integer>() {
public Integer call() throws Exception {
Thread.sleep(new Random().nextInt(5000));
return task;
}
});
}
System.out.println("等待结果");
for (int i=1;i<=10;i++){
System.out.println("结果"+com.take().get());
}
}
}
文章来源:http://www.haha174.top/article/details/253560
项目源码:https://github.com/haha174/thread-learning.git