• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

Notify method notifying all the waiting threads

 
Greenhorn
Posts: 10
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Everyone,
My first post on coderanch.

The problem which I am facing is : When notify() gets called in the below code, all the threads which are waiting gets notified and all starts execution. I am sure this could be a very basic problem but I just couldn't get it. Tried searching on the web, but found no answers unfortunately. Please help me.




Output:
Waiting - Thread-1
Waiting - Thread-2
Sleeping : Thread[Thread-0,5,main]
Notified Thread-1
Notified Thread-2

 
Ranch Hand
Posts: 46
1
Tomcat Server Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dear Batra,

Welcome to Javaranch.

You are synchronizing on instance of thread. If we check the JoinMethodDocumentation, you will see that Thread instance
gets notified when run() method completes. Check the documentation of the join() method.So basically, you execute one explicit notify call
(the one we see in the code), and another implicit notifyAll when the thread is done. We shouldn't synchronize on the Thread object.
Thread toString() methods returns names of all threads in the ThreadGroup, not only name of current Thread. You could even remove your explicit notify
and the behavior wouldn't change due to the implicit notifyAll at the end. Check the modified code below.



HTH,
Ben
 
G Batra
Greenhorn
Posts: 10
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Ben. Actually, the java 6 documentation is not very clear as java 7 documentation. It seems that there's no change in the join implementation as I removed the notify() call, the implicit notifyall() gets called.
http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html#join%28%29

Also, I found an old post on this very same issue.
https://coderanch.com/t/461261/java-programmer-SCJP/certification/notify-notifyAll-code

Thanks again Ben.
 
reply
    Bookmark Topic Watch Topic
  • New Topic