Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Threads ,wait and notify

 
alwin das
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


in this code ThreadA contains the main thread and ThreadB has a thread for calculation.

Now when b.start() is called ,the ThreadB enters into synchronised block and has a lock of the object b;
then how can main thread enters into synchronised(b) and wait method is called?

as every object has only one lock and in this case that is aquired by ThreadB so how can main thread can call wait method (as thread must aquire lock on object to call wait method)


please exlplain this..and correct me
 
Henry Wong
author
Marshal
Pie
Posts: 21195
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now when b.start() is called ,the ThreadB enters into synchronised block and has a lock of the object b;
then how can main thread enters into synchronised(b) and wait method is called?


This is not entirely correct. The main thread merely starts the thread B with the the call to the start() method. It does not call the run() method -- thread B does that.

In starting a thread, it will schedule the thread to run, which may or may not run immediately. In fact, in most cases, the answer is that it will not be running. For you, as a developer, you should design your code to make no assumptions. You should design your code to work regardless if thread B or the main thread runs first.

Henry
 
S Thiyanesh
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lock can be acquired by either the main method, or the run method.
So we shouldn't depend on such unpredictable behavior.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic