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

huangapple go评论61阅读模式
英文:

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

问题

我有一个简单的场景。

我想在循环内部调用一个异步方法(可能是一个API调用)。我想要多次调用同一个API,但在前一个API调用完成之前不要执行下一个API调用。

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

上述方法会正常运行循环10次,而不会等待API调用方法完成。我想要做的是在前一个调用完成后再调用下一个API。

例如:

for(int i = 0; i < 10; i++){
   apicall{
      apiresult
      // 在这个完成后运行下一个循环
   }
}

我尝试使用 while 循环,但速度太慢且不可靠。

英文:

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 &lt; 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 &lt; 10; i++){
   apicall{
      apiresult
     // RUN NEXT LOOP AFTER THIS IS COMPLETE
   }
}

I tried using while loop but it was too slow and not reliable.

答案1

得分: 2

你可以使用递归。大致如下:

void makeAPICalls(int numberOfCalls) {
    numberOfCalls--;
    if (numberOfCalls > 0) {
        apiCall {
            apiResult
            // 当结果到达时再次调用此函数
            makeAPICalls(numberOfCalls)
        }
    }
}

然后你可以这样调用该函数:makeAPICalls(10)

英文:

You could use recursion. Something along these lines:

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

You would then call the function like this: makeAPICalls(10)

huangapple
  • 本文由 发表于 2020年4月10日 16:47:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/61136894.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定