Sleep and check until condition is true

后端 未结 7 2145
借酒劲吻你
借酒劲吻你 2020-12-16 11:39

Is there a library in Java that does the following? A thread should repeatedly sleep for x milliseconds until a condition becomes true or the max t

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-16 12:01

    It seems like what you want to do is check the condition and then if it is false wait until timeout. Then, in the other thread, notifyAll once the operation is complete.

    Waiter

    synchronized(sharedObject){
      if(conditionIsFalse){
           sharedObject.wait(timeout);
           if(conditionIsFalse){ //check if this was woken up by a notify or something else
               //report some error
           }
           else{
               //do stuff when true
           }
      }
      else{
          //do stuff when true
      }
    }
    

    Changer

      synchronized(sharedObject){
       //do stuff to change the condition
       sharedObject.notifyAll();
     }
    

    That should do the trick for you. You can also do it using a spin lock, but you would need to check the timeout every time you go through the loop. The code might actually be a bit simpler though.

提交回复
热议问题