【问题标题】:How to run two ExecutorService invokeAll() in parallel?如何并行运行两个 ExecutorService invokeAll()?
【发布时间】:2022-10-17 23:23:57
【问题描述】:

TLDR:我想同时提交两个可调用列表,但超时时间不同


有没有一种方法或最佳替代方法可以同时运行两个具有不同超时的 invokeAll() 命令?

例如阻塞:

ExecutorService executorService1 = Executors.newFixedThreadPool(2);
ExecutorService executorService2 = Executors.newFixedThreadPool(2);

List<Callable<String>> callableTasks1;
List<Callable<String>> callableTasks2;

List<Future<String>> completed;

completed = executorService1.invokeAll(callableTasks1, 5, TimeUnit.Seconds);
completed.addAll(executorService1.invokeAll(callableTasks2, 2, TimeUnit.Seconds));
for(Future<String> s: completed) {
    if(s.isCancelled()) {
        System.out.println("It's cancelled");
    } else {
       try {
         System.out.println("Got it: " + s.get());
       } 
       catch(...) {
        ...
       }
    }
}

在 for 循环中提交每个任务: executorService.submit(tasks) 并调用 task.get(5, TimeUnit.Seconds) 似乎是按顺序运行的。

【问题讨论】:

  • 除了等待来自多个线程的结果(这是我能想到的同时等待不同次数的唯一方法)之外,可能至少有一种更好的方法可以使用来自CompletableFuture.allOf 的两个复合期货,您在哪里等待在结果上按顺序但在将所有可调用对象提交给执行程序服务之后(您的示例仅使用 executor1 btw)。还要考虑是否真的有理由只给一组任务 2 秒的时间来完成,而在另一组任务上你还要再等 3 秒。
  • (对两者都使用 executor1 是一个错字)。我正在尝试等待来自两个线程的结果,但我仍然必须等待两个线程完成(使用 awaitTermination())。 5和2组成,我原来的区别是5秒(每个都算)我会读到“CompletableFuture.allOf”,并继续寻找选项。谢谢
  • @BasilBourque 已更新

标签: java concurrency executorservice


【解决方案1】:

我最终得到的解决方案是等待两个线程的结果。 此外,我没有为每个调用创建两个线程,而是使用另一个 executorService 来重用线程

缩短版(不运行,修改运行):

ExecutorService executorService1 = Executors.newFixedThreadPool(5);
ExecutorService executorService2 = Executors.newFixedThreadPool(2);

List<Callable<String>> callableTasks1 = new ArrayList(3 callables);
List<Callable<String>> callableTasks2 = new ArrayList(2 callables);

List<Callable<Object>> callableObjectFutures = executorService2.invokeAll(
() -> {executorService1.invokeAll(invokeAll(callableTasks1, 5, TimeUnit.Seconds);},
() -> {executorService1.invokeAll(invokeAll(callableTasks2, 2, TimeUnit.Seconds);}
);

List<Future<String>> completed = callableObjectFutures.get(0).get();
completed.addAll(callableObjectFutures.get(1).get());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多