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

Threads confusion

sarvesh dikonda
Ranch Hand

Joined: Apr 08, 2012
Posts: 58

The below code is from the Threads chapter from SCJP 6 Study Guide-

Snippet 1:


And the question asked is:-
Which of the following pairs of method invocations could NEVER be executing at the same time?
A. x.a() in thread1, and x.a() in thread2 & there are other options too.

But, i just want to clarify the concept that is associated with the one given in option A.
In the book, the explanation given associated with option A is -
A is a right answer because when synchronized instance methods are called
on the same instance, they block each other.

So my doubt is that, from the above explanation, can i conclude that, each thread(i.e thread1 & thread2) are having same copy of object pointed by 'x' that are invoking the synchronized instance method a() ? I am asking this because i am getting confused with the code below.

Snippet 2:


From the above code, both the Threads are using the same or different instance(s) of Dudes as 'd' is marked static which is accessing the synchronized method from Dudes. I am thinking that, if the quoted statements(i.e
A is a right answer because when synchronized instance methods are called
on the same instance, they block each other.
) mentioned above from Snippet 1, is followed for this Snippet 2, then both the Threads here too must block each other, but it does not!

I know there is some difference between Snippet 1 & Snippet 2. But i want to clarify my doubt. So i need your guidance friends.


Always believe in yourself
Himai Minh
Ranch Hand

Joined: Jul 29, 2012
Posts: 722
For code snippet 1, two threads share the same runnable instance. The runnable instance only has one x instance. Two threads share the same x.
The x instance's a method is synchronized. So, two threads access a method of x instance one at a time, not concurrently.

For code snippet 2, there are two DudesChat instances. But they share the same d instance. Since d instance's chat method is synchronized, only one DudesChat instance access chat method one at a time.
 
Consider Paul's rocket mass heater.
 
subject: Threads confusion
 
Similar Threads
Wake up a thread
Need help putting comments in
Another Simple Java Question
Trying to get manageable arrays to work with
Updating page when uploading files