wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Threads ,wait and notify 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 "Threads ,wait and notify" Watch "Threads ,wait and notify" New topic
Author

Threads ,wait and notify

alwin das
Ranch Hand

Joined: Sep 23, 2005
Posts: 32


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
Sheriff

Joined: Sep 28, 2004
Posts: 18757
    
  40

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


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

Joined: Mar 19, 2006
Posts: 142
Lock can be acquired by either the main method, or the run method.
So we shouldn't depend on such unpredictable behavior.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Threads ,wait and notify