• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

about synchronizing

 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic