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)
忙碌等待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)
| 归档时间: |
|
| 查看次数: |
1459 次 |
| 最近记录: |