在某些应用场景下,我们需要获取线程的返回值,采用传统方式或许比较麻烦,那么jdk5为我们封装好了Future和CompletionService。
Future 表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。计算完成后只能使用 get 方法来检索结果,如有必要,计算完成前可以阻塞此方法。取消则由 cancel 方法来执行。还提供了其他方法,以确定任务是正常完成还是被取消了。一旦计算完成,就不能再取消计算。如果为了可取消性而使用Future但又不提供可用的结果,则可以声明 Future<?> 形式类型、并返回 null 作为基础任务的结果。
将生产新的异步任务与使用已完成任务的结果分离开来的服务。生产者 submit 执行的任务。使用者 take 已完成的任务,并按照完成这些任务的顺序处理它们的结果。例如,CompletionService 可以用来管理异步 IO ,执行读操作的任务作为程序或系统的一部分提交,然后,当完成读操作时,会在程序的不同部分执行其他操作,执行操作的顺序可能与所请求的顺序不同。 例子代码如下:
- import java.util.Random;
- import java.util.concurrent.Callable;
- import java.util.concurrent.CompletionService;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.ExecutorCompletionService;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.Future;
-
- public class CallableAndFuture {
-
- public static void main(String[] args) throws InterruptedException, ExecutionException {
-
-
- ExecutorService threadPool = Executors.newSingleThreadExecutor();
-
- Future future = threadPool.submit(
- new Callable<String>(){
-
- public String call() throws Exception {
- Thread.sleep(2000);
- return "Hello";
- }
-
- }
- );
-
- System.out.println("等待结果......");
-
- try {
- System.out.println("拿到结果: " + future.get());
- } catch (InterruptedException e) {
- e.printStackTrace();
- } catch (ExecutionException e) {
- e.printStackTrace();
- }
-
-
- ExecutorService threadPool1 = Executors.newFixedThreadPool(10);
- CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool1);
- for(int i=1; i<=10; i++){
- final int seq = i;
- completionService.submit(
- new Callable<Integer>(){
-
- public Integer call() throws Exception {
- Thread.sleep(new Random().nextInt(5000));
- return seq;
- }
- }
- );
- }
-
- for(int i=0; i<10; i++){
- System.out.println(completionService.take().get());
- }
- }
-
- }