借用一下其他网友案例修改测试如下:
@Test
public void test(){
ExecutorService exec = Executors.newFixedThreadPool(10);
List<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>();
Callable<Integer> task = null;
for (int i = 0; i < 10; i++)
{
final int finalI = i;
task = new Callable<Integer>()
{
@Override
public Integer call() throws Exception
{
int ran = new Random().nextInt(1000);
if(3 == finalI){
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName()+"让第4个任务休眠5秒,使其最后执行完毕" );
}
System.out.println(Thread.currentThread().getName()+" 产生的随机数:" + ran );
return ran;
}
};
tasks.add(task);
}
long s = System.currentTimeMillis();
List<Future<Integer>> results = null;
try {
results = exec.invokeAll(tasks);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("执行任务消耗了 :" + (System.currentTimeMillis() - s) +"毫秒");
for (int i = 0; i < results.size(); i++)
{
try
{
System.out.println(results.get(i).get());
} catch (Exception e)
{
e.printStackTrace();
}
}
exec.shutdown();
}
输出结果如下,虽然第四个提交的任务最后执行完毕,才和其他任务一起返回结果,但第四个任务生成的随机数始终位于返回结果集合的第4个位置
pool-1-thread-1 产生的随机数:422
pool-1-thread-2 产生的随机数:344
pool-1-thread-3 产生的随机数:43
pool-1-thread-5 产生的随机数:378
pool-1-thread-6 产生的随机数:398
pool-1-thread-7 产生的随机数:856
pool-1-thread-8 产生的随机数:142
pool-1-thread-9 产生的随机数:800
pool-1-thread-10 产生的随机数:404
pool-1-thread-4让第4个任务休眠5秒,使其最后执行完毕
pool-1-thread-4 产生的随机数:959
执行任务消耗了 :5081毫秒
422
344
43
959
378
398
856
142
800
404
结束语
返回结果顺序和ExecutorService.invokeAll批量提交任务的顺序相关,即返回列表顺序与提供给执行器的任务顺序相同。有什么问题欢迎留言探讨。