• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

I don't understand this thread code behavior.

 
Tanakorn Numrubporn
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much.
I understand that my problem is relate to OO topic rather than Thread topic.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic