This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
Given a reference called t to a class which extends Thread, which of the following will cause it to give up CPU to allow another thread to execute. a) t.yield(); b) yield(); c) yield(t); d) yield(t); e) Thread.yield() I think , the answer is a) and b) and e) But, the answer says, its just b) and e). Cany plz explain, why not a) is the correct option. I thought a) and e) are almost same. thanks!
public static void yield() Causes the currently executing thread object to temporarily pause and allow other threads to execute.
1) The question seems to deal only with the way of calling to the yield method. Whether the currently executing thread effectively yields or not, depends on the priority of the others threads in the ready state. Only a, b and e are proper ways of calling yield. And b only if the implicit this is of type Thread. 2) t will only stop execution if it is the currently executing thread. If another thread is executing t.yield() that thread will be possible stopped. This a trick possible thanks to yield being static and it can be called on any instance.
The question is faulty! Calling yield() doesn't DEFINITELY stop a thread. I saw a similar question : What MIGHT cause a thread to stop ? 1.wait(), 2.stop(). 3.yield()..... yield() is one of the correct answer. It may or may not cause a thread to stop. Whether calling yield() will stop a thread or not depends on the OS.
This is what I read from Java Certification Guide(-Heller) A thread that has yielded goes to Ready state. There are 2 possible scenarios. If any other threads are in Ready state, then the thread that just yielded might have to wait a while before it gets to execute again. However,if there are no other threads waiting, then the thread that just yielded will get to continue executing immidiately. MOST SCHEDULERS DO NOT STOP THE YIELDING THREAD FROM RUNNING IN FAVOR OF A THREAD OF LOWER PRIORITY. -Mandar Patki