繁体   English   中英

使 for 循环等待方法返回 true

[英]Make a for loop wait till a method returns true

我想让一个 for 循环等待一个方法返回 true。

例如-

   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 开发的新手,所以任何帮助都会非常感激。

为什么不使用“迭代器 for 循环”或“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

}   

按照要求:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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