aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes wait() and synchronization doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "wait() and synchronization doubt" Watch "wait() and synchronization doubt" New topic
Author

wait() and synchronization doubt

Lucas Smith
Ranch Hand

Joined: Apr 20, 2009
Posts: 804
    
    1



Output:
thread 0
main thread

Why does this program print main thread?


SCJP6, SCWCD5, OCE:EJBD6.
BLOG: http://leakfromjavaheap.blogspot.com
Sebastian Janisch
Ranch Hand

Joined: Feb 23, 2009
Posts: 1183
After a Thread has finished, it releases it's locks by calling notifyAll().
Your code calls wait() on t, then the Thread gets to execute and after it finished it calls notifyAll(). Hence no deadlock.

If you wait until the Thread has finished, then call wait() on t, you will run into the deadlock.



JDBCSupport - An easy to use, light-weight JDBC framework -
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

If you do a search of "join implementation detail", you'll get a list of the previous topics about this very subject. In fact, here is my quote from one of the previous topics...

Interestingly, this is actually an artifact of the join() implementation. It was never intended to be a "automatic notification" after the completion of the run() method.

Basically, the join() method will check if the thread is still alive, and if it is, it will call wait() on the thread object. When the run() method completes, it will notifyAll() the threads that are waiting on the thread object -- which supposedly should be all threads that are calling the join() method.


Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Lucas Smith
Ranch Hand

Joined: Apr 20, 2009
Posts: 804
    
    1

Sebastian Janisch wrote:After a Thread has finished, it releases it's locks by calling notifyAll().

It was the key
Thanks.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: wait() and synchronization doubt