[Solved] Java sync class and this by two threads


In your example,

  • All MyThread instances created with id of 1 will synchronize on the MyThread class object. This means that no two MyThread instances can be “in” the first synchonized block at the same time.

  • All MyThread instances created with id of 2 will synchronize on this. Now this is the thread object itself1. Since every thread has a different MyThread, that means that there will effectively be no locking.

  • The run method for an instance with id value 1 will not block an instance with id value 2, 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