In your example,
-
All MyThread instances created with
idof1will synchronize on theMyThreadclass object. This means that no twoMyThreadinstances can be “in” the firstsynchonizedblock at the same time. -
All
MyThreadinstances created withidof2will synchronize onthis. Nowthisis the thread object itself1. Since every thread has a differentMyThread, that means that there will effectively be no locking. -
The run method for an instance with
idvalue1will not block an instance withidvalue2, or vice versa. They are using different locks.
1 – In theory, if one thread could access another thread’s MyThread object, it could explicitly call the run() method on that object. After all, the method is public. In that case, the this would not be the current thread … and therefore you would potentially have locking. However, this is not the kind of thing that a sane programmer would do.
0
solved Java sync class and this by two threads