Yes Sun there are. (Sun as in Sun LiWei, not as in Sun Microsystems... ). Consider the following piece of code:
Imagine that the myMonitor object is not locked by any thread and a thread (let's call it T) attempts to execute the above piece of code. Since the monitor is unlocked, T is able to get hold of it (locks it) and starts executing the code within the synchronized block. As soon as T exits the synchronized block, it releases the lock it holds on myMonitor; thereafter, myMonitor is free of locks and available for locking by another thread that can manage to get hold of it. The difference this scenario has with an invocation of wait() is that a thread invoking wait() on a monitor, would result in the thread being added to the wait set of the monitor, and a subsequent invocation of notify() would result in the thread moving back to a Ready state and competing for locking the object. (don't forget that wait() HAS to be invoked within a synchronized block). On the other hand, when a thread exits a synchronized block it (1) releases the lock and (2) gets out of the competition for the particular monitor altogether. Hope this helps, Panagiotis. SCJP2, January 2001 (91%) IBM Certified Solution Developer VAJ, May 2001 (After that I went on a "certification sabbatical" of sorts ) [ September 12, 2002: Message edited by: Panagiotis Varlagas ]
yield() puts back the running thread to ready state and wait() puts the thread in the waiting pool of the monitor.both are allowing other threads to execute.then why 2 methods to do the same thing?
Joined: Jul 27, 2002
yield() puts back the running thread to ready state and wait() puts the thread in the waiting pool of the monitor.both are allowing other threads to execute.then why 2 methods to do the same thing? is the thread being blocked same as wait()? [ September 13, 2002: Message edited by: pree sree ]
wait() will help in co-ordinating access of shared resources between threads running parallelly. It should be used along with notify()/notifyAll() to achieve this. This is its main objective. But yield() will just put the thread back into the ready queue. It won't help in synchronising access to a shared resource. Both do prevent the current thread from continuing to run, but each has a different purpose. In the case of wait() this is a side-effect. But in the case of yield(), it is the main purpose itself. Again do note that yield() is not guaranteed to allow other threads to execute. Its behaviour depends a lot on the threading model of the operating system. As Marcus rightly reminds us "Garbage collection and threading are 2 areas where java is platform dependent"
Sab<br /> <br />Perfection does not come from belief or faith. Talk does not count for anything. Parrots can do that. Perfection comes through selfless work.<br />Swami Vivekananda