让 for 循环等待方法 returns true

Make a for loop wait till a method returns true

我想让一个 for 循环等到方法 return 为真。

例如-

   for(int i = 0; i < 100; i++)
   {
         // for loop should get executed once

          my_method(i); //this method is called

         // now for loop should wait till the above method returns true

         // once the method returns true the for loop should continue if the condition is true

   }

   public boolean my_method(int number)
   {
      // my code
      return true;
   }

我不知道 my_method() 需要多长时间才能 return 为真。

以上所有代码都在 AsyncTask 中。

我是 Android 开发的新手,所以任何帮助都会非常感激。

根据要求:

private final ReentrantLock lock = new ReentrantLock();
private final Condition done = lock.newCondition();
for(int i=0;i<100;i++)
{
     // for loop should get executed once
 lock.lock();
  try {
         my_method(i, lock); //this method is called
     done.await();
  } finally {
             lock.unlock();
      }

     // now for loop should wait till the above method returns true

     // once the method returns true the for loop should continue if the condition is true

}

public boolean my_method(int number, ReentrantLock lock)
{
  lock.lock();
  try {
    // my code
      done.signal();
  } finally {
      lock.unlock();
  }
return true;
}

你为什么不使用 "iterator for loop" 或 "foreach loop" 而不是只使用 loop.so 循环的每个下一个值将只执行前一个值以及你的方法执行。

但是对于一个选项,您将需要将所有整数的值添加到一个整数数组中,因为这两个选项都适用于一个数组。

//First create an array list of integer and use your same for loop to add all values in that array from 0 to 100

List<Integer> list = new ArrayList<Integer>();

for(int i = 0; i < 100; i++)
{
list.add(i);    
}

//Now you should able to use whether foreach or iterator to execute method for each array (int) value one by one.

//Foreach example:

for (Integer i : list) {

my_method(i); //your method to execute

} 

//Iterator example:

for (Iterator i = list.iterator(); i.hasNext();) {

my_method(i); //your method to execute

}   

我在 for 循环中使用了 while (true)

并且工作正常。

这是我的Detailed Answer.