gpt4 book ai didi

java - 如何使用多线程并行化 Java 中的 for 循环?

转载 作者:行者123 更新时间:2023-11-30 06:01:58 30 4
gpt4 key购买 nike

我正在编写一段代码,它从一个文件中挑选多个 API 调用详细信息并逐个执行这些详细信息,并在 ArrayList 中提供响应数据。以下是我当前的代码。

ArrayList<APICallDetails> apiCallDetailsArray = new ArrayList<>();
APICallDetails apiCallDetails = new APICallDetails();
for (count= 1; count <= callsCount; count++){
try{
apiCallDetails = new APICallDetails();
apiCallDetails.setName(property.getPropertyReader(callName+"_"+count+"_Name", propsFile));
apiCallDetails.setHost(marketConfigs.getRawJson().get(property.getPropertyReader(callName+"_"+count+"_Host", propsFile)).toString().replaceAll("\"", ""));
apiCallDetails.setPath(property.getPropertyReader(callName+"_"+count+"_Path", propsFile));
apiCallDetails.setMethod(property.getPropertyReader(callName+"_"+count+"_Method", propsFile));
apiCallDetails.setBody(property.getPropertyReader(callName+"_"+count+"_Body", propsFile));

apiCallDetails = sendAPIRequest.mwRequestWithoutBody(apiCallDetails, marketConfigs);
BufferedWriter out = null;
try {
out = new BufferedWriter ( new FileWriter ( "C:\\file"+count+".html"));
out.write("something");
out.close();
} catch (IOException e) {
e.printStackTrace();
logger.error(new Date()+" - Error in "+getClass()+".apiCallRequester() flow: "+e.toString());
}

apiCallDetailsArray.add(apiCallDetails);

}catch(NullPointerException e){
e.printStackTrace();
logger.error(new Date()+" - Error in "+getClass()+".apiCallRequester() flow: "+e.toString());
}
}

由于有更多的 API 调用,这是所有调用的响应时间的总和。我希望这些调用并行运行并将响应数据存储在我可以进一步使用的 ArrayList 中。我是 Java 的新手,有人可以帮我解决这个问题吗?

最佳答案

您可以使用并行流。以下调用将并行调用 createAPICallDetails(idx) 并将它们的返回对象添加到 List 中:

    List<APICallDetails> result = IntStream.range(0, callsCount)
.parallel()
.mapToObj(idx -> createAPICallDetails(idx))
.collect(Collectors.toList());

因此,唯一留给您的就是实现以下逻辑:

    APICallDetails createAPICallDetails(int index) { ... }

在给定 index 参数的情况下创建 APICallDetails 的单个对象,以便它可以在前面的 lambda 中使用。

希望这对您有所帮助。

关于java - 如何使用多线程并行化 Java 中的 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56266299/

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