【发布时间】:2023-03-22 22:33:01
【问题描述】:
我有 4 个方法返回不同类的列表。让我们说
public List<A> getA(String param1, String param2){
//some code here
}
public List<B> getB(String param1, String param2){
//some code here
}
public List<C> getC(String param1, String param2){
//some code here
}
public List<D> getD(String param1, String param2){
//some code here
}
我想同时执行这 4 个方法,我使用 Callable 和 Executor 如下所示
Callable<List<A>> collableA = new Callable<List<A>>() {
@Override
public List<A> call() throws Exception {
return getA();
}
};
Callable<List<B>> collableB = new Callable<List<B>>() {
@Override
public List<B> call() throws Exception {
return getB();
}
};
Callable<List<D>> collableD = new Callable<List<D>>() {
@Override
public List<D> call() throws Exception {
return getD();
}
};
Callable<List<C>> collableC = new Callable<List<C>>() {
@Override
public List<C> call() throws Exception {
return getC();
}
};
// add to a list
List<Callable> taskList = new ArrayList<Callable>();
taskList.add(collableA );
taskList.add(collableB);
taskList.add(collableC);
taskList.add(collableD);
//create a pool executor with 4 threads
ExecutorService executor = Executors.newFixedThreadPool(4);
Future<List<FrozenFrameAlert>> futureFrozen = executor.submit(taskList);
// getting error here submit() not accepting taskList
我尝试使用InvokeAll() 和invokeAny() 方法,但没有方法接受这个taskList
【问题讨论】:
-
invokeAll(Collection<? extends Callable<T>> tasks)应该可以工作。你是如何使用它或你得到什么错误?executor.submit只接受一个任务。 -
如果我使用
invokeAll()得到这个错误The method invokeAll(Collection<? extends Callable<T>>) in the type ExecutorService is not applicable for the arguments (List<Callable>)对于submit()得到这个错误The method submit(Callable<T>) in the type ExecutorService is not applicable for the arguments (List<Callable>)
标签: java executorservice