简体   繁体   中英

Pause a method until it gets called again

I have this method run() which executes a whole lot of other methods. In these sub-methods, there's a counter which increments with 1 in some sub-methods. When this counter reaches a given number n , the method run() should be paused for an undetermined time. When it's called again, it should start executing where it left before pausing.

Is this possible in Java?

Edit : some more information as asked by Andersoj

I tried to strip down my code a lot. This is a very basic example of what it looks like.

public void run(int n) {
   executeA();
}

public void executeA() {
   while (randomCondition) {
      executeB();
      counter++;
   }
   executeC();
   if (counter <= 100)
      executeD();
}

The code in executeA() should run until counter equals n . It doesn't matter until where it is executed, it should pause (this can happen anywhere in executeA() .

After a while, run() is called again, the code should resume where the thread previously stopped in executeA() .

Thanks again!

If your stopping and resuming is based on a given condition, and assuming that the method would be woken up by some other thread that could make the condition change (none of the premises is clear in your question):

public void run() {
   synchronized(mutex){
      while(condition){
         try {
            mutex.wait();
         }catch(InterruptedException e) {//...}
      }
      goOn();
   }
}

Alternatively, you can wait an arbitrary amount of time using mutex.wait(waitTime) .

Your other thread would wake the waiting thread when the condition changes or it will wake up again some time after the waiting time is up, in whose case the condition will be re-evaluated and it may enter into the waiting state again if the condition has not changed.

public void run() {
   synchronized(mutex){
     if(condition){
         mutex.notify();
     }
   }
}

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