我有一些代码,如下所示:效率 - 循环使用Thread.yield的是等待变量的变化
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
我知道,可能有一个更正式的方式来实现使用锁或AsynchronousTasks这种模式,但这种方法效果很好的时刻,是非常明显的,所以为什么改变?
你可以实现'wait-notify'模式 – 2013-04-25 06:14:10
'timeout()'做什么? – SimonC 2013-04-25 06:14:31
我在这里使用timeout()来表示任何类型的超时条件以确保活跃性。在我的情况下,它检查System.currentTimeMillis()对于在while循环之前进行的测量 – Alex 2013-04-25 07:17:40