简体   繁体   English

我们应该在执行超时操作时使用Thread.sleep()吗?

[英]Should we use Thread.sleep( ) when doing something with timeout?

Consider the following two blocks: 考虑以下两个块:

    // block one
    long start = System.currentTimeMillis();
    while (System.currentTimeMillis() - start < TIMEOUT) {
        if( SOME_CONDITION_IS_MET ) {
            // do something
            break;
        } else {
            Thread.sleep( 100 );
        }
    }

    // block two
    long start = System.currentTimeMillis();
    while (System.currentTimeMillis() - start < TIMEOUT) {
        if( SOME_CONDITION_IS_MET ) {
            // do something
            break;
        }
    }

The difference between the two is that the first one has a Thread.sleep(), which seemingly can reduce condition checking in while and if . 两者之间的区别在于第一个有一个Thread.sleep(),它似乎可以减少条件检查whileif However, is there any meaningful benefit by having this sleep, assuming the if condition doesn't have a heavy computation? 但是,假设if条件没有繁重的计算, if通过这种睡眠是否有任何有意义的好处? Which one would you recommend for implementing timeout? 你会推荐哪一个实现超时?

One key difference is that the second method involves busy waiting . 一个关键的区别是第二种方法涉及忙碌等待 If SOME_CONDITION_IS_MET doesn't involve any I/O, the second approach will likely consume an entire CPU core. 如果SOME_CONDITION_IS_MET不涉及任何I / O,则第二种方法可能会占用整个CPU内核。 This is a wasteful thing to do (but could be perfectly reasonable in some -- pretty rare -- circumstances). 这是一件很浪费的事情(但在某些情况下可能完全合理 - 非常罕见)。 On the flip side, the second approach has lower latency. 另一方面,第二种方法具有较低的延迟。

I agree with Boris that, in a general setting, both approaches are basically hacks. 我同意鲍里斯的观点,在一般情况下,这两种方法基本上都是黑客攻击。 A better way would be to use proper synchronization primitives to signal the condition. 更好的方法是使用适当的同步原语来指示条件。

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

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