睡觉并检查,直到情况成立 [英] Sleep and check until condition is true

查看:138
本文介绍了睡觉并检查,直到情况成立的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中是否有一个库可以执行以下操作?一个线程应该重复 sleep x毫秒,直到条件变为真或达到最大时间。

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 time is reached.

这种情况主要发生在测试等待某些条件变为真时。条件受另一个线程的影响。

This situation mostly occurs when a test waits for some condition to become true. The condition is influenced by another thread.

为了让它更清晰,我希望测试到在失败之前只等待X ms。它不能永远等待条件成为现实。我正在添加一个人为的例子。

Just to make it clearer, I want the test to wait for only X ms before it fails. It cannot wait forever for a condition to become true. I am adding a contrived example.

class StateHolder{
    boolean active = false;
    StateHolder(){
        new Thread(new Runnable(){
            public void run(){
                active = true;
            }
        }, "State-Changer").start()
    }
    boolean isActive(){
        return active;
    }
}


class StateHolderTest{
    @Test
    public void shouldTurnActive(){
        StateHolder holder = new StateHolder();
        assertTrue(holder.isActive); // i want this call not to fail 
    }
}


推荐答案

编辑

大多数答案都集中在低级API上,包括等待和通知或条件(更多或更多或不一样的方式):当你不习惯它时,很难做到正确。证明:其中2个答案没有正确使用等待。

java.util.concurrent 为您提供了一个高级API,其中隐藏了所有这些错综复杂的内容。

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 就是这样:


  • 当条件成立时,在等待的线程中调用 latch.countdown();

  • ,使用: boolean ok = latch.await (1,TimeUnit.SECONDS);

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

Contrived example:

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

注意:CountDownLatches是线程安全的。

Note: CountDownLatches are thread safe.

这篇关于睡觉并检查,直到情况成立的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆