本篇说明的是Callable和Future,它俩颇有意思的,一个产生结果,一个拿到结果。 java
Callable接口相似于Runnable,从名字就能够看出来了,可是Runnable不会返回结果,而且没法抛出返回结果的异常,而Callable功能更强大一些,被线程执行后,能够返回值,这个返回值能够被Future拿到,也就是说,Future能够拿到异步执行任务的返回值,下面来看一个简单的例子:编程
public class CallableAndFuture { public static void main(String[] args) { Callable<Integer> callable = new Callable<Integer>() { public Integer call() throws Exception { return new Random().nextInt(100); } }; FutureTask<Integer> future = new FutureTask<Integer>(callable); new Thread(future).start(); try { Thread.sleep(5000);// 可能作一些事情 System.out.println(future.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }
FutureTask实现了两个接口,Runnable和Future,因此它既能够做为Runnable被线程执行,又能够做为Future获得Callable的返回值,那么这个组合的使用有什么好处呢?假设有一个很耗时的返回值须要计算,而且这个返回值不是马上须要的话,那么就可使用这个组合,用另外一个线程去计算返回值,而当前线程在使用这个返回值以前能够作其它的操做,等到须要这个返回值时,再经过Future获得,岂不美哉!这里有一个Future模式的介绍:http://openhome.cc/Gossip/DesignPattern/FuturePattern.htm。 多线程
下面来看另外一种方式使用Callable和Future,经过ExecutorService的submit方法执行Callable,并返回Future,代码以下:并发
public class CallableAndFuture { public static void main(String[] args) { ExecutorService threadPool = Executors.newSingleThreadExecutor(); Future<Integer> future = threadPool.submit(new Callable<Integer>() { public Integer call() throws Exception { return new Random().nextInt(100); } }); try { Thread.sleep(5000);// 可能作一些事情 System.out.println(future.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }
代码是否是简化了不少,ExecutorService继承自Executor,它的目的是为咱们管理Thread对象,从而简化并发编程,Executor使咱们无需显示的去管理线程的生命周期,是JDK 5以后启动任务的首选方式。 dom
执行多个带返回值的任务,并取得多个返回值,代码以下:异步
public class CallableAndFuture { public static void main(String[] args) { 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++) { try { System.out.println(cs.take().get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } } }
其实也能够不使用CompletionService,能够先建立一个装Future类型的集合,用Executor提交的任务返回值添加到集合中,最后遍历集合取出数据,代码略。性能
这里再阐述一下:提交到CompletionService中的Future是按照完成的顺序排列的,这种作法中Future是按照添加的顺序排列的。线程
因此这两种方式的区别在于:code
1. CompletionService.take 会获取并清除已经完成Task的结果,若是当前没有已经完成Task时,会阻塞。htm
2. “先建立一个装Future类型的集合,用Executor提交的任务返回值添加到集合中,最后遍历集合取出数据”——这种方法一般是按照Future加入的顺序。
两个方法最大的差异在于遍历 Future 的顺序,相对来讲, CompletionService 的性能更高。考虑以下场景:多线程下载,结果用Future返回。第一个文件特别大,后面的文件很小。用方法1,能很快知道已经下载完文件的结果(不是第一个);而用方法2,必须等第一个文件下载结束后,才会得到其余文件的下载结果。