سؤال

I am calling the below process method from a different class in a main thread.

Now what I want to do is, in the first iteration of the for loop, I will call checkValue method and see whether it returns true or false. If it returns false, then I would like to sleep for 2 minutes and then again call checkValue method after sleeping to see whether it returns true or false or not, and again if it returns false, then I will sleep again for two minutes and then I will try calling checkValue method again and if it returns true now, then only I will go to next iteration of for loop.

public void process(String name) {

    ..// some other code here

    for (int i = 1; i <= 10; i++) {
        try {
            .. // some other code here

            if (!checkValue()) {
                Thread.sleep(120000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


private boolean checkValue() throws Exception {
    boolean check_nodes = false;
    return check_nodes;
}

Is there any way to do this?

هل كانت مفيدة؟

المحلول

Why not simply us a while loop and not an if block nested in a for loop?

while (!checkValue()) { 
  try {
    Thread.sleep(SLEEP_VALUE);
  } catch (InterruptedException ie) {
    // do something if interrupted...
  }
} 
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top