简体   繁体   English

如何在 java 中同步循环,以便我可以手动增加循环值(当某些执行完成时)

[英]How to synchronize loop in java so I could increment loop value manually (when some execution is complete)

I have a simple scenario.我有一个简单的场景。

I want to make calls to a async method (probably an api call) inside loop.我想在循环内调用异步方法(可能是 api 调用)。 I want to call the same api multiple times but don't execute the next api call until previous one is complete.我想多次调用相同的 api 但在前一个调用完成之前不要执行下一个 api 调用。

for(int i = 0; i < 10; i++){
   apicall{
      apiresult
   }
}

The above method will run the loop 10 times normally without waiting for the api call method to be finished.上述方法将正常运行循环 10 次,无需等待 api 调用方法完成。 what I want to do is call the next api after previous one is complete.我想做的是在前一个完成后调用下一个 api。

For example:-例如:-

for(int i = 0; i < 10; i++){
   apicall{
      apiresult
     // RUN NEXT LOOP AFTER THIS IS COMPLETE
   }
}

I tried using while loop but it was too slow and not reliable.我尝试使用while循环,但它太慢且不可靠。

You could use recursion.你可以使用递归。 Something along these lines:这些方面的东西:

void makeAPICalls(int numberOfCalls) {
    numberOfCalls--;
    if (numberOfCalls > 0) {
        apiCall {
            apiResult
            // when result arrives call this again
            makeAPICalls(numberOfCalls)
        }
    }
}

You would then call the function like this: makeAPICalls(10)然后,您可以像这样调用 function: makeAPICalls(10)

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

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