我有 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
最佳答案
只需对每个可调用对象使用submit()
;这将为您提供四种 future ,每种 future 都有正确的类型:
Future<List<A>> futureA = executor.submit(callableA);
Future<List<B>> futureB = executor.submit(callableB);
etc.
如果您在继续之前需要所有四个 future 的结果,您可以依次阻塞每个:
List<A> resultA = futureA.get();
List<B> resultB = futureB.get();
etc.
要进行更一般化的操作,您需要找出所有这些列表都“相同”的方法。但是,如果您不以相同的方式使用它们,那么它们是不同的类型并不重要。
关于java - 如何在 Java 中使用 Executors 执行返回不同对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47937185/