• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

yield();

 
manasa teja
Ranch Hand
Posts: 325
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
from the api for yield

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.
 
Alan Chong
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Mandar Patki
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Tybon Wu
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the answer should only be e) Thread.yield() because yield() could be overridden, such as this example:

In the above example, calling t.yield() or yield() will do nothing. Calling Thread.yield() is the only way to guarantee the desired behaviour.
[ July 01, 2002: Message edited by: Tybon Wu ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic