我有一些如下所示的代码:
while (this.conditionIsNotYetMet){
if (timeout()) break;
// Don't do anything, just wait till the condition is
// filled by a different thread or timeout occurs.
}
performSomeCode(); // this code relies on the condition having been met
代码有效 - 最终另一个线程满足条件,代码执行。
我很好奇加入 Thread.yield() 是否是一个好主意 - 无论哪种方式似乎都是正确的,在这个阶段我感觉不到性能差异 - 但我担心将来它可能会有所作为,例如在不同的平台上。
即代码将成为
while (this.conditionIsNotYetMet){
if (timeout()) break;
Thread.yield(); // <---- CHANGE IS HERE!!!!
// Don't do anything, just wait till the condition is
// filled by a different thread or timeout occurs.
}
performSomeCode(); // this code relies on the condition having been met
我知道使用锁或异步任务可能有一种更正式的方式来实现这种模式,但是这个解决方案目前运行良好并且足够清晰,那么为什么要改变呢?