效率 - 循环使用Thread.yield那等待变量的变化 [英] Efficiency - use of Thread.yield in loop that waits for variable change

查看:307
本文介绍了效率 - 循环使用Thread.yield那等待变量的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些code,看起来像以下内容:

I've got some code that looks like the following:

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

在code工作 - 最终另一个线程充满的情况下,和code执行

The code works - eventually the other thread fills the condition, and the code executes.

我很好奇,这是否会成为,一Thread.yield()抛出一个好主意 -​​ 这似乎是正确的无论哪种方式,在这个阶段,我感觉不到性能差异 - 但我担心,在未来它可能会有所作为,比如在不同的平台。

I'm curious as to whether or not it would be a good idea to throw in a Thread.yield() - it seems to be correct either way, and at this stage I can't feel a performance difference - but I'm concerned that in the future it might make a difference, e.g. on a different platform.

即。 code将成为

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这种模式,但这种方法效果很好的时刻,是非常明显的,所以为什么要改变?

I'm aware that there's probably a much more formal way to achieve this pattern using locks or AsynchronousTasks, but this solution works well at the moment and is clear enough, so why change?

推荐答案

收益率()是在你的其他线程看到停滞的情况下非常有用。换句话说,你有一个非常活跃的线程以某种方式总是比其他线程,从来没有真正得到做任何事情的优先级更高。调用收益率()从活动的线程迫使它给换到另一个正在运行的线程。

yield() is useful in the cases where you are seeing stagnation on other threads. In other words, you have a very active thread that's somehow always taking priority over some other thread that never really gets to do anything. Calling yield() from your active thread forces it to give change to another running thread.

如果你的程序是为你的例子一样简单,你也许并不需要调用的产量,再加上取决于如何超时()实现(如果它有一个视频下载()的Object.wait()内部)同样会导致隐式上下文切换就像产量会。

If your program is as simple as your example, you probably do not need to call yield, plus depending on how timeout() is implemented (if it has a Thread.sleep() or Object.wait() inside) it will also implicitly result a context switch just like yield would.

所以,你不需要写它,但你可能得到它的影响已经无妨。

So, you do not need to write it, but you're probably getting the effects of it already anyway.

PS:极端codeRS指出,你可能想使用等待通知的模式,这里的为例

PS: As Extreme Coders points out, you probably want to use a wait-notify pattern, here's an example

这篇关于效率 - 循环使用Thread.yield那等待变量的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆