ExecutorService.invokeAll批量执行任务,返回的 Future 列表的顺序与提供的 Callable 对象的列表顺序是否相同?

借用一下其他网友案例修改测试如下:

  @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批量提交任务的顺序相关,即返回列表顺序与提供给执行器的任务顺序相同。有什么问题欢迎留言探讨。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值