yield() doesn't "PROMISE" other threads to execute. yield() promises to give other threads an OPPORTUNITY to execute by returning the thread back to the runnable state allowing a new thread to run. The thread chosen to run is from the group of threads waiting in the runnable state which the original thread is now a part of. So it is very possible that the original thread may be chosen to continue running.
From K&B - In reality, though, the yield() method isn't guaranteed to do what it claims, and even if yield() does cause a thread to step out of running and back to runnable, there's no guarantee the yielding thread won't just be chosen again over all the others.
Hi, Tom. Thanks for your explanation. But yield won't promise that the current thread will yield other threads. The current thread may execute until it is finished without yielding, just as the previous post said.
Helen Ma wrote:In my opinion, I think the answer should be sleep. The current thread will sleep and let other threads execute.
But why the answer is yield?
Anyone can help?
I thought that too. sleep should be the answer.
In K&B book it says "Using sleep() is the best way to help all threads get a chance to run! Or at least to guarantees that one thread doesn't get in and stay until it's done.
Hi Helen and Janki. I think it depends on how the question is interpreted and what terms are important. The key terms being promises and undefined moment.
Your both correct that 'the same thread might start executing again' or that the JVM can ignore the yield() and continue running the thread.
I think its a poorly written question but in terms of the question (as I interpret it), I still think yield() is the correct answer.
Good chance I'm wrong with this but the way I see it is:
yield() does 'promise' to pause. Whether the JVM responds to that yield() or not is up to the JVM. Doesn't mean that it's going to happen, just that it promises to yield for other threads if the JVM wants to take advantage of it. Whereas the sleep() method essentially guarantees that it will take a break as Janki stated from the book.
The other term would be how you read 'undefined moment.' Does that mean some amount of time that you just haven't told about (N) or does that mean a method that doesn't require a parameter of time? I'm reading it as the latter which would fit the yield() method versus an undefined amount of time (N) that would be used as a parameter for the sleep() method.
Again, I think its a poorly written question that is open to interpretation and I could easily defend sleep() being the correct answer. I feel bad for suspend(). RIP.
If you settle for what they are giving you, you deserve what you get. Fight for this tiny ad!
Free, earth friendly heat - from the CodeRanch trailboss