File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Threads - K&B Exercise 9-2 -" Watch "Threads - K&B Exercise 9-2 -" New topic
Author

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.

Thanks
Deepak Bala
Bartender

Joined: Feb 24, 2006
Posts: 6657
    
    5

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Threads - K&B Exercise 9-2 -
 
Similar Threads
Thread Join method
Synchronizing question
locks and monitor
KATHY SCJP 1.6 : THREADS, exercise 9-2. Is my code fine?
Threads blocking on static method.... or do they?