Sleep and check until condition is true

后端 未结 7 2122
借酒劲吻你
借酒劲吻你 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 11:48

    EDIT

    Most answers focus on the low level API with waits and notifies or Conditions (which work more or less the same way): it is difficult to get right when you are not used to it. Proof: 2 of these answers don't use wait correctly.
    java.util.concurrent offers you a high level API where all those intricacies have been hidden.

    IMHO, there is no point using a wait/notify pattern when there is a built-in class in the concurrent package that achieves the same.


    A CountDownLatch with an initial count of 1 does exactly that:

    • When the condition becomes true, call latch.countdown();
    • in your waiting thread, use : boolean ok = latch.await(1, TimeUnit.SECONDS);

    Contrived example:

    final CountDownLatch done = new CountDownLatch(1);
    
    new Thread(new Runnable() {
    
        @Override
        public void run() {
            longProcessing();
            done.countDown();
        }
    }).start();
    
    //in your waiting thread:
    boolean processingCompleteWithin1Second = done.await(1, TimeUnit.SECONDS);
    

    Note: CountDownLatches are thread safe.

提交回复
热议问题