This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Threads - K&B Exercise 9-2 - Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Threads - K&B Exercise 9-2 -" Watch "Threads - K&B Exercise 9-2 -" New topic

Threads - K&B Exercise 9-2 -

d jones
Ranch Hand

Joined: Mar 13, 2006
Posts: 76
I have a question about the solution for excercise 9-2 in Chapter 9 on page 555 of the K&B book for SCJP 1.4.

I have written a program for the exercise and what they are saying is correct but I am a little confused as to why it is behaving the way it does.

In the main method in this program there are 3 new objects created and each starts its own thread.

When the first object runs the thread prints out 'A's and it then increments the character to B - that's fine.

However, when the second object runs its thread it prints out the character 'B' and then increments the character.

I would have expected the second object to print A again here since 3 different objects are each starting threads.

I'm not clear how or why the second thread printed 'B's -- it somehow had access to the member variable in the object that the first thread was working on.

Could anyone please explain to me how the second thread was able to pickup the character that the first thread incremented.

I thought the three new statements in main created 3 new objects and the thread (run method) would work on each object's contents individually.

Deepak Bala

Joined: Feb 24, 2006
Posts: 6662

I would guess that either you passed the same object instance to all three threads to work on, or you were accessing a static variable. Could you post the code here please.

SCJP 6 articles - SCJP 5/6 mock exams - More SCJP Mocks
d jones
Ranch Hand

Joined: Mar 13, 2006
Posts: 76
Here is the code:

Shaliey Gowtham
Ranch Hand

Joined: Mar 20, 2006
Posts: 104
Here you are using the same instance of StringBuffer for the three threads so the original object is always modified three times.
If you were using the three different instances of the StringBuffer for the three threads then "A" will be printed by the three threads.
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: Threads - K&B Exercise 9-2 -
It's not a secret anymore!