gpt4 book ai didi

java - 如何并行而不是顺序执行多个模型?

转载 作者:行者123 更新时间:2023-11-29 05:12:15 25 4
gpt4 key购买 nike

我有各种模型,我正在按顺序一个接一个地执行这些模型。我将有大约 200 个模型。

下面是我的代码,我在其中一个一个地执行这些模型

Map<String, List<ServerMetrics>> metricsHolder = new HashMap<String, List<ServerMetrics>>();

for (String alias : serverNames) {
List<ClientsModel> modelMetadata = getModelAttributes();
List<MachineInfo> machineInfo = getMachineInfo();

List<ServerMetrics> metricsList = new ArrayList<ServerMetrics>();

// calling model one by one sequentially
// is there any way to make this multithreaded?
// here modelMetadata size might be 100 or 200
for (ClientsModel modelList : modelMetadata) {
String modelValue = modelList.getModelValue();
String modelId = String.valueOf(modelList.getModelId());

// execute my model here and storing the metrics in the metricsList object
ServerMetrics metrics = TestUtils.executeModelMetrics(machineInfo, modelValue);
metrics.setModelId(modelId);

metricsList.add(metrics);
}

metricsHolder.put(alias, dynMetricsList);
}

问题陈述:-

有什么方法可以使模型执行多线程,然后将结果存储到 metricsList 对象中?

最佳答案

如果您的代码中没有数据竞争条件(多线程访问未正确同步的相同数据),那么您可以使用线程池,以 ExecutorService 的形式,在线程上运行 Callable 实现。您可以在 Callable 中完成这项工作。

在主线程上,ExecutorService 返回一个 Future,然后您可以等待所有任务都已生成。

线程池的大小(此处设置为 10,但您可以更改它)决定并行运行的数量。您仍然可以执行比线程池大小更多的 Callable

    Map<String, List<ServerMetrics>> metricsHolder = new HashMap<String, List<ServerMetrics>>();
// Size of thread pool set at 10 - can be increased but increasing it
// to more than the number of cores on your computer is probably not
// useful, as it seems like your task is CPU-bound
ExecutorService executorService = Executors.newFixedThreadPool(10);

for (String alias : serverNames) {
List<ClientsModel> modelMetadata = getModelAttributes();
List<MachineInfo> machineInfo = getMachineInfo();

List<Future<ServerMetrics>> metricsFutureList = new ArrayList<Future<ServerMetrics>>();

// calling model one by one sequentially
// is there any way to make this multithreaded?
for (ClientsModel modelList : modelMetadata) {
final String modelValue = modelList.getModelValue();
final String modelId = String.valueOf(modelList.getModelId());

metricsFutureList.add(executorService.submit(new Callable<ServerMetrics>() {
@Override
public ServerMetrics call() throws Exception {

// execute my model here and storing the metrics in the list
ServerMetrics metrics = TestUtils.executeModelMetrics(machineInfo, modelValue);
metrics.setModelId(modelId);
return metrics;
}
}));

}
List<ServerMetrics> metricsList = new ArrayList<ServerMetrics>();
for (Future<ServerMetrics> future : metricsFutureList) {
metricsList.add(future.get());
}
metricsHolder.put(alias, dynMetricsList);
}

关于java - 如何并行而不是顺序执行多个模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28007872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com