如何并行运行两个ExecutorService invokeAll()



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循环中提交每个任务:executerService1.submit(task(和调用task.get(5,TimeUnit.Seconds(似乎在按顺序运行。

我最终得到的解决方案是等待来自两个线程的结果。此外,我没有为每个调用创建两个线程,而是使用了另一个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());

相关内容

  • 没有找到相关文章

最新更新