【java】并发执行ExecutorService的sumbit返回值的顺序问题
ArrayList<Future> fl = new ArrayList<Future>();
for (int i = 0; i < 10; i++) { Future<String> future = executorService.submit(new TaskWithResult(i)); fl.add(future); }
for(int i = 0;i<fl.size();i++){ System.out.printf("future.get() = " + fl.get(i).get()); System.out.println(""); }
一开始,我以为 executorService.submit中先执行完的任务的返回结果集会存在fl的前面,但是经过测试发现,却并非如此。
测试代码:
public void test() throws InterruptedException, ExecutionException{ ExecutorService executorService = Executors.newCachedThreadPool(); int j = 0; @SuppressWarnings("rawtypes") ArrayList<Future> fl = new ArrayList<Future>(); for (int i = 0; i < 10; i++) { Future<String> future = executorService.submit(new TaskWithResult(i)); fl.add(future); } for(int i = 0;i<fl.size();i++){ System.out.printf("future.get() = " + fl.get(i).get()); System.out.println(""); } } class TaskWithResult implements Callable<String> { private int id; public TaskWithResult(int id) { this.id=id; } @Override public String call() throws Exception { ArrayList<String> s = new ArrayList<String>(); for(int i = 0; i < (10-id)* 10000 ;i++){ String s1 = String.valueOf(id) + ':' + String.valueOf(i); s.add(s1); } System.out.println("完成: " + id); return String.valueOf(id); } }
执行后输入如下:
完成: 5 完成: 7 完成: 6 完成: 4 完成: 8 完成: 9 完成: 3 完成: 2 完成: 1 完成: 0 future.get() = 0 future.get() = 1 future.get() = 2 future.get() = 3 future.get() = 4 future.get() = 5 future.get() = 6 future.get() = 7 future.get() = 8 future.get() = 9
这表明,不管是哪个任务先完成,在返回值列表中的顺序是一样的。这个是如何实现的呢?
Future<V>代表一个异步执行的操作,通过get()方法可以获得操作的结果,如果异步操作还没有完成,则,get()会使当前线程阻塞。