Yield inside synchronized block? Lock release after calling yield()?

跟風遠走 提交于 2020-01-04 04:31:10

问题


I am creating a multiple threads and calling yield() inside it.

The java.lang.Thread.yield() method causes the currently executing thread object to temporarily pause and allow other threads to execute.

Will It be possible for other threads to execute which also want to go inside synchronized block?

synchronized(this.lock)
{
 //calling yield here.

}

thanks.


回答1:


As far as I know, Yield() only gives up the remaining time slice on the CPU and steps back in the queue. It doesn't release any synchronized objects.




回答2:


yield does not take or release locks, it simply pauses the current thread execution. So yielding in the synchronized block will not let the current thread to release lock and let the other methods to enter the synchronized block. wait/notify method should be used to release the lock.

From Java Language Specification

Thread.sleep causes the currently executing thread to sleep (temporarily cease execution) for the specified duration, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors, and resumption of execution will depend on scheduling and the availability of processors on which to execute the thread.

It is important to note that neither Thread.sleep nor Thread.yield have any synchronization semantics. In particular, the compiler does not have to flush writes cached in registers out to shared memory before a call to Thread.sleep or Thread.yield, nor does the compiler have to reload values cached in registers after a call to Thread.sleep or Thread.yield.




回答3:


yield allows a context switch to other threads, so this thread will not consume the entire CPU usage of the process. The thread still holds the lock. It is the developer responsibility to take care of deadlocks.



来源:https://stackoverflow.com/questions/18635616/yield-inside-synchronized-block-lock-release-after-calling-yield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!