While studying for the exam I'm trying some examples. This one made me wonder. The variant that synchronises a block works fine, but the one that synchronises a method doesn't. I'd appreciate if someone can shed some light on this puzzle.
In both your examples, you have three
thread (testsync) objects holding a reference to the same
string buffer object.
In the first case, the three threads are synchronizing on the same (string buffer) object, so hence, they will block while another is holding the lock.
In the second case, the three threads are synchronizing on the "this" object. Unfortunately, the three threads are using different TestSync objects, so have different "this" objects, and hence, they will never contend for a lock.
Henry