简体   繁体   English

Java使用Thread.sleep()或继续询问

[英]Java use Thread.sleep() or go keep asking

I have scenario: I want to wait, until something is false. 我有一个场景: 我想等到错误。 Usually takes likes 20 seconds or so. 通常需要20秒左右。

while(foo) {
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

Or just go like this? 还是就这样走?

while(foo) {

}

Busy waiting for 20 seconds is not a good idea - and sleeping for 5 seconds means you might miss the signal by 5 seconds. 忙于等待20秒不是一个好主意-睡眠5秒钟意味着您可能会错过5秒钟的信号。 Can't you use a different way, such as a CountdownLatch : 您不能使用其他方式,例如CountdownLatch

CountDownLatch latch = new CountDownLatch(1);

//code that triggers the signal
latch.countDown();

//code that waits for the signal
try {
    latch.await();
} catch (InterruptedException e) {
    //handle interruption
}

It this is just a unit test, I would use the first example. 这只是一个单元测试,我将使用第一个示例。 It doesn't have to be pretty. 不一定要漂亮。

If this is production code, you are better off using a different structure such a Condition or a Future. 如果这是生产代码,则最好使用其他结构,例如“条件”或“未来”。

The second form is going to burn a lot of CPU cycles. 第二种形式将消耗大量CPU周期。 It will check as fast as it can, maybe a hundred thousand times per second. 它会以最快的速度检查,也许每秒十万次。 That's not a good idea. 那不是一个好主意。

Thread.sleep() is better, a little. Thread.sleep()更好一点。 You still have another problem here if foo is a non-volatile field and/or this is not in a synchronized block. 如果foo是一个非易失性字段和/或它不在synchronized块中,则您在这里还有另一个问题。 It is not actually guaranteed that it will ever see an update from another thread. 实际上并不能保证它会看到另一个线程的更新。

Use primitives in java.util.concurrent for this like CountDownLatch . 为此,请使用java.util.concurrent原语,例如CountDownLatch

For sure, the second form can not be used. 当然,第二种形式不能使用。 That can hog the CPU and cause problems. 这会占用CPU并引起问题。 The first form is better. 第一种形式更好。

What is going to change the value? 什么会改变价值?

If it is just another thread then you can consider using wait / notify or any of the concurrency constructs. 如果只是另一个线程,则可以考虑使用wait / notify或任何并发构造。

Does nobody like Wait/Notify any more? 没有人喜欢“等待/通知”了吗? It's effcient, simpler than the Sleep() loop bodges and less typing than 'CountDownLatch'., 它比Sleep()循环复杂,效率高,比'CountDownLatch'少键入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM