简体   繁体   English

为什么Java中的yield方法不释放锁?

[英]Why yield method in java does not release the lock?

I have some doubt regarding the yield method in java. 我对java中的yield方法有一些疑问。 Because when we are using it like Thread.yield() then the thread goes to the runnable state and give chance to the other thread to run but the thread which call yield is not releasing the lock. 因为当我们像Thread.yield()这样使用它时,线程进入可运行状态并给其他线程运行机会,但是调用yield的线程没有释放锁。 So , only threads except those who are waiting for the lock to release will run . 因此,只有那些正在等待释放锁的线程才会运行。 So , when and in which scenario this yield method is useful. 因此,何时,在哪种情况下使用此yield方法。

Thread.yield() is useful in an environment that provides co-operative rather than pre-emptive threading. Thread.yield()在提供Thread.yield()而不是抢先式线程的环境中很有用。 In other words, if the OS will not suspend your thread to let another run. 换句话说,如果操作系统不会暂停您的线程以让另一个线程运行。 In such an environment, you should regularly call yield() when performing a CPU-intensive operation. 在这种环境下,执行CPU密集型操作时应定期调用yield()

I don't know of any modern operating systems that support Java but don't support pre-emptive threading, so it has little/no use in modern Java programs. 我不知道任何支持Java但不支持抢占式线程的现代操作系统,因此在现代Java程序中几乎没有使用。

Thread.yield() has nothing to do with locks, is not documented to affect locks in any way, and should not be used in the assumption that it will release a lock. Thread.yield()与锁无关 ,没有文档证明它以任何方式影响锁,并且不应在假定它将释放锁的情况下使用Thread.yield()


Edit: this SO answer has much more information on how Thread.yield() is implemented (at least as-of JDK 1.6). 编辑: 此SO答案具有有关如何实现Thread.yield()更多信息(至少自JDK 1.6起)。

I agree with @kdgregory, Thread.yield() probably should not be used in modern Java programs. 我同意@kdgregory,可能不应该在现代Java程序中使用Thread.yield()。 But, it's not because allowing one thread to yield to others is a bad idea: It's just because, if you really need to yield(), then you probably are re-inventing an algorithm that is already implemented in java.util.concurrent. 但是,这并不是因为让一个线程屈服于其他线程不是一个坏主意:这仅仅是因为,如果您确实需要yield(),那么您可能正在重新发明一种已经在java.util.concurrent中实现的算法。


One thing's for sure: If you're going to yield(), don't do it inside a synchronized block. 可以肯定的一件事:如果要使用yield(), 不要在同步块内进行操作。 The whole point of yield() is to let other threads run. yield()的要点是让其他线程运行。 The whole point of a synchronized block is "I want to finish this bit before any other thread gets to start it." 同步块的全部要点是“我想在任何其他线程启动它之前先完成此位”。

Your goal should always be to make sure your program spends as little time in synchronized blocks as possible. 您的目标应该始终是确保程序在同步块中花费的时间尽可能少。 The more time it spends in synchronized blocks, the less it will benefit from multiple processors. 它花在同步块上的时间越长,则从多个处理器中受益的机会就越少。 Every synchronized block is a bottleneck. 每个同步块都是一个瓶颈。 Even a small one can make a big difference. 即使是很小的人也可以有很大的不同。 Read about Amdahl's Law. 阅读有关阿姆达尔定律的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM