StringBuffer sb = new StringBuffer("A"); SyncExample t1 = new SyncExample(sb); SyncExample t2 = new SyncExample(sb); SyncExample t3 = new SyncExample(sb); t1.setName("A"); t2.setName("B"); t3.setName("C"); t1.start(); t2.start(); t3.start(); } } And it works fine, but if I change the lock for the this instance (synchronized (this) instead of synchronized (sb)) I don�t get the expected result. The threads access the synchronized block interchangeably, and that is not correct. And if you saw the example named AccountDanger (page 706) you would see that the synchronized method makeWithdrawal, works fine, the object Account, which is referenced by acct, is accessed by one thread at a time. And as I understand it, the method makeWithdrawal locks on the this instance. Why does this last example present a different behavior than the exercise 9-2 when it locks on the this instance?
This is a normal behavior. All the three threads share the same StringBuffer object but all of them are separate instances of SyncExample class. So each of them will have a separate this. This is the reason that if you synchronize of this, then access the StringBuffer interchangeably as they all hold locks to their own instance which is not common between them. [ September 02, 2008: Message edited by: Ankit Garg ]
Ankit, thank you for your answer. Now I think I understand why the example AccountDanger works fine. Because the instance that the threads share is the same, and the lock is on that instance (n). The this instance refers to the object whose reference variable is (n). Am I right?
AccountDanger n = new AccountDanger(); Thread one = new Thread(n); Thread two = new Thread(r); one.setName("Fred"); two.setName("Lucy"); one.start(); two.start();