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

Jaa*_*nus 0 java multithreading sleep

我有情景:我想等,直到某些事情是假的.通常需要20秒左右.

while(foo) {
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)

或者就这样去?

while(foo) {

}
Run Code Online (Sandbox Code Playgroud)

ass*_*ias 9

忙碌等待20秒并不是一个好主意 - 睡眠5秒意味着您可能会错过5秒的信号.你不能使用不同的方式,例如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
}
Run Code Online (Sandbox Code Playgroud)