ExecutorService 提交方法返回的期货不维护提交顺序

ExecutorService submit method returned futures not maintaining the order of submission

大家好,我对所有 java 并发的东西都很陌生,如果我的问题听起来有点天真,请原谅我。问题是我正在尝试将任务循环提交给执行程序服务,并立即返回列表中返回的未来。现在在另一个循环中,我正在遍历期货列表并调用 get on the future 以获得实际结果。现在困扰我的是,我希望未来与提交的顺序相同,但我得到的是完全随机的 order.Here 是我的代码

for (int count = 0; count < product_ID_List.size(); count++) {
                System.out.println(product_ID_List.get(count));
                WebServiceCall WebServiceCall = new WebServiceCall(basePath, product_ID_List.get(count),
                        companyId);
                futureList.add(executor.submit(WebServiceCall));
            }

web 服务调用基本上是在数据库中插入一条记录和 returns 自动生成的 id

这是迭代未来列表的代码

for (int count = 0; count < futureList.size(); count++) {
                Response resp = futureList.get(count).get();
                BResponse bresponse = new BResponse();
                bresponse = resp.readEntity(BResponse.class);
                System.out.println("the generated id is @ " + bresponse.generatedPOID);

            }

现在完全新鲜 table 我通常希望结果为 1,2,3,因为第一个提交的任务会生成 id 1 等等,但我得到的结果是随机的,例如 3 ,1,2 2,3,1 等等.. 需要帮助我怎样才能按照任务的顺序维护期货 submitted.Note 而不是谈论任务的执行顺序。

这里你的期货没有改变它的顺序。您将按照提交任务的相同顺序获得 future.get()。但是,您已经看到 id 的顺序不是顺序的,因为您首先提交的 任务确实保证它将首先执行 。因此,您提交的第一个任务可能会最后执行(或任何顺序),因此在此之前可能已经执行了 n 个任务,因此当该任务执行时,它将获得 id (n+1) 而不是 1future.get() 将 return 你 (n+1)