ExecutorService.submit()会返回一个future.
blic static void main(String[] args) { 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) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); }
运行结果:
等待结果
等待结果hello
而如果使用CompletionService.submit方法,会在多个任务运行时,按照完成的先后顺序依次返回,看代码:
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(5000)); return seq; } }); } for(int i=0;i<10;++i){ try { System.out.println(completionService.take().get()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
运行结果:
2
8
0
1
5
3
6
7
4
9