[英]Waiting for something to finsih, should I use thread.sleep or ReentrantLock?
[英]Should we use Thread.sleep( ) when doing something with timeout?
考虑以下两个块:
// 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;
}
}
两者之间的区别在于第一个有一个Thread.sleep(),它似乎可以减少条件检查while
和if
。 但是,假设if
条件没有繁重的计算, if
通过这种睡眠是否有任何有意义的好处? 你会推荐哪一个实现超时?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.