Forums Register Login

Problem with excirse 9-2

+Pie Number of slices to send: Send
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?
+Pie Number of slices to send: Send
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 ]
+Pie Number of slices to send: Send
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();
I am not a spy. Definitely. Definitely not a spy. Not me. No way. But this tiny ad ...
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 1044 times.
Similar Threads
Excercise 9-2
What Happens If a thread Can't Get the Lock?
Threads and synchronisation
Threads: synchronizing a block of code (K&B 1.5)
Syncronizing variables or classes - Exercise 9-2
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 17:59:44.