简体   繁体   中英

Make a for loop wait till a method returns true

I want to make a for loop wait till a method returns true.

For 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;
   }

I don't know how long will my_method() take to return true.

All the above codes are inside a AsyncTask.

I am new to Android Development so any help would be really Grateful.

Why don't you use "iterator for loop" or "foreach loop" instead of just for loop.so every next value of loop will execute only then a previous value along with your method executed.

But for an option, you will require to add all integer's values in an array of integer because both options work with an array.

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

}   

As requested:

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;
}

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