aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes I don't understand this thread code behavior. 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 "I don Watch "I don New topic
Author

I don't understand this thread code behavior.

Tanakorn Numrubporn
Ranch Hand

Joined: Dec 11, 2006
Posts: 81
This is the code:


the output is:
AAAAAAAAAABBBBBBBBBBCCCCCCCCCC

The question is; when I instance one I send "A" to the HimThread constructor and two I also send "A" to the HimThread constructor and so do three.

Why the output is not be:
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

Thank you
Anton Uwe
Ranch Hand

Joined: Jan 10, 2007
Posts: 122
Hi Tanakorn,

1st, AAAAAAAAAABBBBBBBBBBCCCCCCCCCC is a possible output sequence, but i.e. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAC or AAAAAAAAAABBBBBBBBBBBBBBBBBBBB are also possible output sequences. Let's see why.
In the main-method "StringBuffer sb = new StringBuffer("A")" will create a StringBuffer object, referenced by sb.
By "HimThread one = new HimThread(sb)" this reference is passed to the constructor, and by "sb = s;" in the constructor the reference to our StringBuffer object will be copied into the "HimThread one"s StringBuffer sb - reference.
The same happens in the next two lines of the code for HimThread two and three. Each HimThread has a StringBuffer reference, but all are referring to our StringBuffer Object created in the main method.
As long as no thread has done its work, they will print "A"s. As soon as the first of them has finished his for-loop, he will execute "sb.setCharAt(0, (char)(sb.codePointAt(0)+1));", so the "A" will be changed to "B" in the StringBuffer object sb is referring (and that is our StringBuffer object created in main). When the second Thread finished his loop, he will change the "B" to "C" and the last will change it to "D".

Hope this will help you to understand it better...
Tanakorn Numrubporn
Ranch Hand

Joined: Dec 11, 2006
Posts: 81
Thank you very much.
I understand that my problem is relate to OO topic rather than Thread topic.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: I don't understand this thread code behavior.