进行for循环等待,直到方法返回true

时间:2017-06-24 10:00:57

标签: java android loops for-loop wait

我想做一个for循环等待,直到方法返回true。

对于Eg -

   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()需要多长时间才能返回true。

以上所有代码都在AsyncTask中。

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

2 个答案:

答案 0 :(得分:1)

为什么不使用“迭代器迭代器”或“ foreach循环”,而不是仅使用for循环。因此,循环的每个下一个值将只执行前一个值,然后再执行方法。

但是对于一个选项,您将需要在整数数组中添加所有整数值,因为这两个选项都可以与数组一起使用。

//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

}   

答案 1 :(得分:0)

根据要求:

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;
}
相关问题