IT程序员开发必备-各类资源下载清单,史上最全IT资源,个人收藏总结!
1、Future取得的结果类型和Callable返回的结果类型必须一致,这是通过泛型来实现的。
2、Callable要采用ExecutorSevice的submit方法提交,返回的future对象可以取消任务。
3、CompletionService用于提交一组Callable任务,其take方法返回已完成的一个Callable任务对应的Future对象。
(1) 好比我同时种了几块地的麦子,然后就等待收割。收割时,则是那块先成熟了,则先去收割哪块麦子。
例子程序:
package edu.java5.threadpool; 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) { ExecutorService threadPool = Executors.newSingleThreadExecutor(); /* * threadPool的execute(Runnable)方法调用不能返回结果,submit(Callable)方法调用可以返回结果, * 返回的结果封装在Future对象中 */ Future<String> future = threadPool.submit(new Callable<String>() { @Override public String call() throws Exception { Thread.sleep(2000); return "hello"; } }); System.out.println("等待结果..."); //通过调用future.get()取得结果 try { //future.get()下面的代码须取得后才能被执行 System.out.println("取得结果:"+future.get()); System.out.println("已经取得!"); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } /** * CompletionService用于提交一组Callable任务,其take方法返回已完成的一个Callable任务对应的Future对象。 **/ ExecutorService threadPool2 = Executors.newFixedThreadPool(10); CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool2); for (int i = 0; i < 10; i++) { final int seq = i; completionService.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { Thread.sleep(new Random().nextInt(6000)); System.out.println(Thread.currentThread().getName()+" execute the Callable and return "+seq); return seq; } }); } for (int i = 0; i < 10; i++) { try { System.err.println(completionService.take().get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } System.out.println("全部取完!"); } }
输出:
等待结果... 取得结果:hello 已经取得! pool-2-thread-6 execute the Callable and return 5 5 pool-2-thread-8 execute the Callable and return 7 7 pool-2-thread-9 execute the Callable and return 8 8 pool-2-thread-10 execute the Callable and return 9 9 pool-2-thread-2 execute the Callable and return 1 1 pool-2-thread-5 execute the Callable and return 4 4 pool-2-thread-1 execute the Callable and return 0 0 pool-2-thread-7 execute the Callable and return 6 6 pool-2-thread-3 execute the Callable and return 2 2 pool-2-thread-4 execute the Callable and return 3 3 全部取完!