I resolve the excirse this way:
public class SyncExample extends Thread{
private StringBuffer sb;
public SyncExample (StringBuffer sb){
this.sb = sb;
}
public StringBuffer getSb() {
return sb;
}
public void run (){
synchronized (sb){
if (this.sb !=null){
for (int i = 1; i <= 100; i++){
System.out.println(Thread.currentThread().getName() + " i " + i + " "+ this.sb);
}
char ch0 = this.getSb().charAt(0);
ch0++;
this.getSb().setCharAt(0, ch0);
}
}
}
public static void main(
String[] args) {
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?