• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

KnB notify(), wait(), synchronized block

 
Richard Teston
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Dhanashree Mankar
Ranch Hand
Posts: 123
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 787
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic