【发布时间】:2013-04-25 06:10:52
【问题描述】:
我有一些如下所示的代码:
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模式 -
timeout()是做什么的? -
我在这里使用 timeout() 来表示任何类型的超时条件以确保活力。在我的例子中,它检查 System.currentTimeMillis() 与 while 循环之前进行的测量
标签: java multithreading asynchronous