java - 如何在 Java 中使用 Executors 执行返回不同对象的方法

标签 java executorservice

我有 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/

相关文章:

java - 如何消除 2 个不同类的 util 类上的重复项

java - 使用selenium在浏览器中打开多个网址

amazon-web-services - AWS lambda 中的执行器服务

java - 为什么与 ScheduleExecutorService 一起运行的 UserThread 没有被垃圾收集

Java ExecutorService堆空间问题

java - 是否可以中断 ExecutorService 的特定线程?

java - 尝试通过同一个套接字发送文件和字符串(在 Java 中)

java - 如何管理执行者

java - 如何创建实现接口(interface)的抽象类对象(JAVA)

java - 如何配置 ExecutorService newFixedThreadPool() 行为?