File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

wait() and synchronization doubt

 
Lucas Smith
Ranch Hand
Posts: 808
1
Android Eclipse IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Output:
thread 0
main thread

Why does this program print main thread?
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
Henry Wong
author
Marshal
Pie
Posts: 20834
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Lucas Smith
Ranch Hand
Posts: 808
1
Android Eclipse IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sebastian Janisch wrote:After a Thread has finished, it releases it's locks by calling notifyAll().

It was the key
Thanks.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic