Hi, so does notify() makes the thread relinquish the lock on that object? Also what is the differentce bewteen notify() and notifyAll()? Do they both let ALL threads know that the lock to this object is available?
notify() and notifyALL() send triggers to threads that are suspended because they called wait(). This is distinct from the object lock, which is held by any thread that happens to be running code marked as "synchronized". In other words, a thread will block when it hits a "synchronized" method that is currently being run by another thread, but this situation is nothing to do with wait() and notify() (it's just that wait() and notify() can only be called within a synchronized method). 1) so does notify() makes the thread relinquish the lock on that object? No. The lock on the object is only released when the synchronized method is exited. What notify does is send a trigger to a currently "wait()"-ing thread so that it can restart when the lock is eventually released. 2) Also what is the differentce bewteen notify() and notifyAll()? Do they both let ALL threads know that the lock to this object is available? notify() only lets ONE thread that is currently "wait()"ing that it can get going again (after the lock is released, as above). Offhand, I THINK it will be the one that has been waiting the longest, but I'm not sure that's guaranteed. notifyALL() lets ALL currently wait()"ing threads know that they can start when the lock's released.
The thread that gets awakened as a result to a call to notify or notifyAll is implementation dependent. It is not guaranteed to be the thread that has been waiting the longest or has the highest priority. If you need to control the thread that gets awakened, I would suggest looking at Tom Cargill's Specific Notification pattern at http://www.sni.net/~cargill/jgf/9809/SpecificNotification.html Also, notifyAll will awaken all threads but only one will get the lock and execute, the others will block. When wait is called, the thread relinquishes its lock and goes into a wait state. When notifyAll is called, all threads waiting on the lock are awakened, but only one gets the lock...and without special code like in the pattern above, you can't determine which thread that will be. Peter Haggar ------------------ author of: Practical Java