The code below is from K&B's book, it will print out 100 As, then 100 Bs, finally 100 Cs. My question is at line 23-25, three anonymous objects are created and they are different objects, and since "letter" is an instance variable rather than an class variable, there should be three "letter" variables on three separated stack, the operation in run() method should not affect the "letter" in others' stacks, therefor it should print 300 As. But they do print 100 As, then 100Bs, then 100Cs, could anybody tell me why? Thanks in advance.
1. class InSync extends
Thread {
2. StringBuffer letter;
3.
4. public InSync(StringBuffer letter) {
5. this.letter = letter;
6. }
7.
8. public void run() {
9. synchronized(letter) {
10. for(int i = 1;i<=100;++i) {
11. System.out.print(letter);
12. }
13. System.out.println();
14. // Increment the letter in StringBuffer:
15. char temp = letter.charAt(0);
16. ++temp;
17. letter.setCharAt(0, temp);
18. }
19. }
20.
21. public static void main(
String [] args) {
22. StringBuffer sb = new StringBuffer("A");
23. new InSync(sb).start();
24. new InSync(sb).start();
25. new InSync(sb).start();
26. }
27. }
[ August 31, 2003: Message edited by: Dep Joy ]
[ August 31, 2003: Message edited by: Dep Joy ]