Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Thread.yield()

Status
Not open for further replies.

drkestrel

MIS
Sep 25, 2000
439
0
0
GB
Is it true that if I am using multi-threading Thread.yield() (which I think puts a thread in a runnable/ready to run state) would NOT release any monitor/mutext/lock that the Thread currently owns?
 
This is true. Basically causing a Thread to yield is playing nice. An example is if you have a GUI thread that has just prompted the user for input than it stands to reason that there is no purpose for the GUI Thread to continue to hold the CPU. The chances are that it will take a second or two for the user to actually input the necessary data, this is a lot of CPU time that is wasted if your Thread is just sitting there spinning its wheels. A better design would be to yield the CPU since you don't actually need it and allow other Threads to execute. The drawback is that if the GUI Thread holds an important monitor than it could be blocking other Threads from execution but in this case it doesn't matter because we were going to be waiting anyways. Obviously explicitly calling yield is not advantageous in all cases. Regardless, even if you do not ever explicitly call yield the JVM is going to timeslice the different based on their priority. It is not like in C when you needed to explicitly control threading in your code if the OS didn't support it (okay so POSIX threading was at least better than this). It doesn't matter if the OS supports threads or not the JVM will emulate a multi-threaded system. A great thing about Java is that threading is directly built into the language so it is very easy to take advantage of. The drawback is that it is very easy to abuse as well.
 
Hmm...

so if I have

Thread A waiting for a synchronized lock X from Thread B and
Thread B waiting for a synchronized lock Y from Thread A

Then calling Thread.yield from either thread is not going to help then... :-(
 
I don't know how you can say that the JVM will 'emulate' threading if the OS doesn't support it. I'd like to see some literature.

The fact of the matter is Java threads map to the OS threads. I think you'd find it difficult to run java on a true 'unthreaded' OS.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top