Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

java - Does Thread.yield() do anything if we have enough processors to service all threads?

If we are in a situation with two running threads on a machine with two processors and we call Thread.yield() within one of those threads, does it stand to reason that nothing will happen (the scheduler will essentially ignore the request) because we have enough processors to service the running threads?

question from:https://stackoverflow.com/questions/56043933/does-thread-yield-do-anything-if-we-have-enough-processors-to-service-all-thre

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Whenever a thread calls the Thread.yield() method, it gives a hint to the thread scheduler that it is ready to pause its execution. The thread scheduler is free to ignore this hint.

If any thread executes the yield method, the thread scheduler checks if there is any runnable (waiting to be executed) thread with same or high priority than this thread. If the processor finds any thread with higher or same priority then it will switch to a new thread. If not, the current thread keeps executing.

Since, in your example, you have enough processors to service all the Threads (they are running, not waiting in a runnable state); Thread.yield() will do nothing, and your threads will continue their execution.

A note about Windows, from Microsoft DOTNet:

This method is equivalent to using platform invoke to call the native Win32 SwitchToThread function.

Yielding is limited to the processor that is executing the calling thread. The operating system will not switch execution to another processor, even if that processor is idle or is running a thread of lower priority. If there are no other threads that are ready to execute on the current processor, the operating system does not yield execution

So there may be caveats in some situations.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...