my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes KnB notify(), wait(), synchronized block Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "KnB notify(), wait(), synchronized block" Watch "KnB notify(), wait(), synchronized block" New topic
Author

KnB notify(), wait(), synchronized block

Richard Teston
Ranch Hand

Joined: Feb 12, 2002
Posts: 89
In the following code:

I know when you call wait() method the thread that get holds of the lock releases the lock but in this case when synchronized(r)invoked means the main user-thread acquire the lock on the r object (before r.wait() is been called) which job1 user-thread already acquired the lock.
Isn't it that object has only one lock? Em i missing something out here?


The Code is the Programmer
Dhanashree Mankar
Ranch Hand

Joined: Aug 25, 2003
Posts: 123
i think your code is perfectly all right
thread scheduling is platform dependent. so which thread will start executing first we cann't say. i executed this code on my system here main thread is firstly getting a lock on object r . when it enters into wait state child thread gets entry in synchronised method in JobRunnable class.
then it notifies main thread , completes it's execution and then main thread starts and completes.
May be sometimes child thread gets the lock first. In that case when it enters into sleep state ,main thread will get the lock and then will enter into wait. again when child comes out of sleep it will notify main .
Barkat Mardhani
Ranch Hand

Joined: Aug 05, 2002
Posts: 787
I was going through some old thread related posts for more practice. Found this one which I do not completely agree:
May be sometimes child thread gets the lock first. In that case when it enters into sleep state ,main thread will get the lock and then will enter into wait. again when child comes out of sleep it will notify main .

My points:
1. When a thread goes to sleep, it takes lock with it.
2. After child thread will wake from sleep naturally, it will be dead.
3. Then main thread will resume.
4. It will wait for ever because there is no live thread to notify it.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: KnB notify(), wait(), synchronized block
 
Similar Threads
Thread Locks
Help correct this calculator thread
After notify()
notify() vs notifyAll()
runtime exception with respective to thread program