Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

about synchronizing

 
Wai Yip Lau
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am preparing for SCJP and get confused in some codes provided by the reference book. Here's the code:

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. }

The aim of the code is to show that three threads are attempting to manipulate the same object and use synchronizing a block to solve it. I don't understand why its the same object. Each thread is created by new and should be three different object/thread, so in run() each thread should be varing their own variable(letter). How come they are varing the same variable???

Thank You.
 
Wai Yip Lau
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh, I think I get the answer.
Is that the three threads have their own reference variable by are refering to the same object?
 
Vlado Zajac
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Wai Yip Lau:

Is that the three threads have their own reference variable by are refering to the same object?

Yes. They have their own reference variables, all refering to the same object (the object is created at line 22).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic