In your example,
-
All MyThread instances created with
id
of1
will synchronize on theMyThread
class object. This means that no twoMyThread
instances can be “in” the firstsynchonized
block at the same time. -
All
MyThread
instances created withid
of2
will synchronize onthis
. Nowthis
is 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
id
value1
will not block an instance withid
value2
, 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