There can be any number of waiting threads ready to continue but that are waiting for the thisObject lock.
From another thread (and synchronized on thisObject) calling thisObject.notify() will make one of the waiting
threads runnable. Calling thisObject.notifyAll() will make all the waiting threads runnable and the JVM will start
allocating time to each. This code launches 10 threads. It then calls notify() followed by notifyAll().
Jim ... ...
Vishal Hegde wrote:Hi,
does that means that it wakes up the object that was locked?
Object won't go to sleep....
If a Thread got the lock for a particular object, then that Thread doing some works on that object, and other Threads, which want that object lock to do their job, is waiting, and the notifyAll() method notifies that the currently working Thread has finished its job. So others can try to acquire the lock of that particular object.
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Joined: Jan 09, 2008
Remember that there is only one logical CPU to share across all the threads. Notice
that main() launches the new threads in code that is not synchronized. So it completes
the 10 launches as it is granted time to do so. As each new thread enters run() and is granted
the shared lock, wait() is called. This suspends the thread and releases the lock. The next new
thread does the same. (Each thread is paused in the middle of synchronized code.)
Meanwhile, the main thread now wants the lock also, to call notify(). (The sleep(200) is included
to help assure that all 10 threads are waiting before the main thread gets the lock. There is no
guarantee of this but it seems to work.) main() calls notify(), releases the lock, and immediately
asks for it again.
It is interesting that the lock is now granted to one of the 10 waiting threads rather than giving
it back to main(). The selected thread picks up where it left off; it prints the "continue..." message,
releases the lock and dies. At this point the other 9 threads are still paused, waiting to regain
the lock, but the single notify() has been consumed. The lock can now be granted back to main()
where notifyAll() is called and the lock is released again.
Abimaran : I think this is where your question comes in. The JVM sees that notifyAll() has been
called, and the lock is available, so it grants it to another of the paused threads. When this thread
completes its work and releases the lock, it is granted to another, and so-on until all the paused
threads have been restarted.
Calling notify() causes the JVM to pick just one paused thread, give it the lock and stop. For
notifyAll(), the JVM continues down its list of waiting threads as the lock becomes available.