简体   繁体   中英

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. I want to call the same api multiple times but don't execute the next api call until previous one is complete.

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. what I want to do is call the next api after previous one is complete.

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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