简体   繁体   English

如何控制Java Futures“提交”的订单?

[英]How to control orders in which Java Futures are “submitted”?

In this example, i am submitting a few files to my comparator object. 在这个例子中,我向比较器对象提交了一些文件。 It all works fine, except that i noticed that order in which files are submitted is not always teh same order in which they are returned. 这一切都很好,除了我注意到提交文件的顺序并不总是与它们返回的顺序相同。 Any suggestions on how i can better control this? 关于如何更好地控制这个的任何建议?

 ExecutorService pool = Executors.newFixedThreadPool(5);
  CompletionService<Properties> completion = new ExecutorCompletionService<Properties>(pool);

  for (String target : p.getTargetFiles()) {
   completion.submit(new PropertiesLoader(target, p));
  }

  for (@SuppressWarnings("unused")
  String target : p.getTargetFiles()) {
   Properties r = null;
   try {
    r = completion.take().get();
   } catch (InterruptedException e) {
    e.printStackTrace();
   } catch (ExecutionException e) {
    e.printStackTrace();
   }

   p.addTargetFilesProperties(r);
  }

  pool.shutdown();

The main point of using CompletionService.take is to have it return whichever Future has finished, no matter what order they were submitted. 使用CompletionService.take的主要目的是让它返回Future完成的任何一个,无论它们提交的顺序如何。 If you want to return them in order you might as well not use that at all (you might not even want to use CompletionService at all, but you can). 如果你想按顺序返回它们,你可能根本不使用它(你可能根本不想使用CompletionService ,但你可以)。 Keep a list of the Future objects returned from submit() and call .get() on each one; 保留从submit()返回的Future对象列表,并在每个对象上调用.get() ; it will block until the result is available. 它会阻塞,直到结果可用。

When submitting multiple tasks to the ThreadPoolExecutor at once, you have no real control on the termination times, since they are being executed by multiple threads concurrently. 当一次向ThreadPoolExecutor提交多个任务时,您无法真正控制终止时间,因为它们是由多个线程同时执行的。 The completion service returns them in the order they complete, which may vary from one execution to another. 完成服务按照它们完成的顺序返回它们,这可能因执行而异。 If you decide to execute the task serially, the completion order is the same as the activation order. 如果您决定按顺序执行任务,则完成顺序与激活顺序相同。

--EDIT-- - 编辑 -

If you still want concurrency, but want to wait for the tasks in a specific order, don't use the completion service. 如果您仍想要并发,但希望按特定顺序等待任务,请不要使用完成服务。 Simply loop on the futures in the required order, and call their get() method, which blocks if necessary. 只需按所需顺序循环到期货,并调用它们的get()方法,如果需要,它会阻塞。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM