The difference between synchronized object locks and class locks

object lock

If synchronized is added to a method, the object lock is used

class lock

If static and synchronized are added to a method, then a class lock is used.

The difference between object locks and class locks

  • The object lock is an object. If multiple methods in the same class only have synchronized, and multiple threads use an object to run the synchronization method at the same time, but only one thread runs the synchronization method, other threads have to wait
  • If static and synchronized are added to multiple methods in the same class, then the obtained lock is a class lock, which is also called a static synchronization lock. Of course, class locks only focus on those that have static and synchronized in the same class. method
  • In addition, object locks and class locks are different. They do not affect each other. They are two locks without affiliation. When one thread acquires a class lock, another thread can acquire an object lock.
  • If neither synchronized nor static is added to the methods in the above-mentioned class, then there is no need to obtain object locks or class locks, and there is nothing wrong with how many threads call these methods at the same time
  • In addition, you need to know that the sleep() method means that the thread executing the method sleeps with a lock, and the thread still holds the lock when it wakes up.

おすすめ

転載: blog.csdn.net/weixin_54046648/article/details/128182044