posted 21 years ago
Dear all,
It's a little bit complex example, but someone can explain me why this code doesn't seem to be synchronized although it should be?
Indeed, when I run it, the output is:
Thread1-989, -237
Thread2-989, -487
As I interpret, this happens:
Thread1 run() executes this: rect.width = rect.width - 500 = 11 -500 = -489;
Thread.yield() -> Thread1 must not move out of the virtual CPU because of synchronization
Thread1 continues: rect.height -= 13 => rect.height = 13 - 250 = -237;
now Thread2 begins its execution:
rect.width = rect.width - 500 = -489 -500 = -989;
and just after that Thread2 moves out the CPU so that Thread1.run method can execute:
System.out.println(getName() + ss.rect.width + ss.rect.height);
=> Thread1 -989 , -237
but how is it possible since the block where width and height are set is supposed to be synchronized and that lock can't be given up in the middle?
I'm perplexed of what really happens here,
I would be very grateful for any help,
Cyril.
SCJP 1.4, SCWCD, SCBCD, IBM XML, IBM Websphere 285, IBM Websphere 287