简体   繁体   English

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

[英]How to use multi-threading to parallellize a for loop in Java?

I am writing a code which picks the multiple API call details from a file and executes those ones by one and provides the response data in an ArrayList.我正在编写一个代码,它从文件中选择多个 API 调用详细信息并逐个执行这些调用,并在 ArrayList 中提供响应数据。 Below is my current code.下面是我目前的代码。

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());
        }
    }

As there are more API calls, this is taking the sum of the response time of all the calls.由于有更多 API 调用,这是所有调用的响应时间的总和。 I want these calls to run parallelly and store the response data in an ArrayList which I can use further.我希望这些调用并行运行并将响应数据存储在我可以进一步使用的 ArrayList 中。 I am new to Java so, can someone please help me with this?我是 Java 新手,请问有人可以帮我吗?

You can use parallel streams.您可以使用并行流。 The following invocation will invoke in parallel createAPICallDetails(idx) and add their return objects into a List :以下调用将并行调用createAPICallDetails(idx)并将其返回对象添加到List

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

So, the only thing left for you is to implement the logic of:因此,剩下的唯一事情就是实现以下逻辑:

    APICallDetails createAPICallDetails(int index) { ... }

To create a single object of your APICallDetails given the index argument, so it can be used in the previous lambda.在给定index参数的情况下创建APICallDetails的单个对象,以便它可以在之前的 lambda 中使用。

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM