This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes about synchronizing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "about synchronizing" Watch "about synchronizing" New topic
Author

about synchronizing

Wai Yip Lau
Greenhorn

Joined: Jun 20, 2005
Posts: 23
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

Joined: Jun 20, 2005
Posts: 23
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

Joined: Aug 03, 2004
Posts: 245
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).
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: about synchronizing
 
Similar Threads
threads ... from K&B
Threads Doubt
synchronizing a block of code
Synchronized block of code
Doubt in exercise 9-2,K&B -Threads