Could someone explain two me why these to codes dont output the same results (the only difference between two codes is in the run() method) ?
NB: the first code seems not doing any lock!
First Code:
class LetterThread extends Thread
{
private StringBuffer letter;
public static void main(String[] args) {
StringBuffer sbltr = new StringBuffer("A");
LetterThread one = new LetterThread(sbltr);
LetterThread two = new LetterThread(sbltr);
LetterThread three = new LetterThread(sbltr);
one.setName("Thread ONE");
two.setName("Thread TWO");
three.setName("Thread THREE");
one.start();
two.start();
three.start();
}
LetterThread(StringBuffer letter) {
this.letter = letter;
}
public synchronized void run() {
{
for (int x = 0; x < 100; x++) {
System.out.println(Thread.currentThread().getName() + " (" + x
+ ") = " + letter);
}
letter.setCharAt(0, (char) (letter.charAt(0) + 1));
}
}
}
Second Code: this code is working exactely as expecting to
class LetterThread extends Thread
{
private StringBuffer letter;
public static void main(String[] args) {
StringBuffer sbltr = new StringBuffer("A");
LetterThread one = new LetterThread(sbltr);
LetterThread two = new LetterThread(sbltr);
LetterThread three = new LetterThread(sbltr);
one.setName("Thread ONE");
two.setName("Thread TWO");
three.setName("Thread THREE");
one.start();
two.start();
three.start();
}
LetterThread(StringBuffer letter) {
this.letter = letter;
}
public void run() {
synchronized (letter) {
for (int x = 0; x < 100; x++) {
System.out.println(Thread.currentThread().getName() + " (" + x
+ ") = " + letter);
}
letter.setCharAt(0, (char) (letter.charAt(0) + 1));
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…