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.