java - why this synchronized method is not working as expected? -
Does anyone give me two reasons that the code does not have the output difference (the difference between the two codes is only in the run ) Method:?
NB: The first code is not locking any!
First Code:
Expand the square LetterThread thread {Private stringbuff letter; Public static zero main (string [] args) {stringbuffer sbltr = new stringbuffer ("A"); LetterThreadAd = New LetterTrad (SLLTR); LetterThread two = new lettertread (SLLTR); LetterThread three = new LetterThread (sbltr); One.setName ("Thread One"); Two .setName ("thread to"); Three .setName ("Thread Three"); One.start (); Two.start (); Three.start (); } LetterThread (stringbuff letter) {this.letter = letter; } Public synchronized run () ({int x = 0; x & lt; 100; x ++} {System.out.println (Thread.currentThread (). GetName () + "(" + + x + ") =" + Letter); } Letter.setCharAt (0, (four) (letter.charAt (0) + 1)); }}}
Second Code: This code is working properly
class extends the LetterThread thread { Private stringbuff letter; Public static zero main (string [] args) {stringbuffer sbltr = new stringbuffer ("A"); LetterThreadAd = New LetterTrad (SLLTR); LetterThread two = new lettertread (SLLTR); LetterThread three = new LetterThread (sbltr); One.setName ("Thread One"); Two .setName ("thread to"); Three .setName ("Thread Three"); One.start (); Two.start (); Three.start (); } LetterThread (stringbuff letter) {this.letter = letter; } Public Zero Run () {Synchronize (Letter) {for (int x = 0; x & lt; 100; x ++) {System.out.println (Thread currentThread (). GetName () + "(" + + X + ") =" + letter); } Letter.setCharAt (0, (four) (letter.charAt (0) + 1)); }}
first code
This is the thing that you have 3 instances of threads and each thread runs its synchronized
method due to run ()
. But there is always a single thread which is defeated to synchronize it with its own run ()
method, so whenever threads want to run it will run, resulting in no synchronization.
Second Code
You have 3 instances of the thread, but they share a reference for the letter object If you lock this context, the threads will be exiting each other and the code runs as expected.
Additional Information
This post tells very well why the first solution does not work:
Comments
Post a Comment