difference between synchronizing a static method and a non static method

后端 未结 7 1325
一向
一向 2020-12-02 11:27

What is the difference between synchronizing a static method and a non static method in java?Can anybody please explain with an example. Also is there any difference in sync

相关标签:
7条回答
  • 2020-12-02 12:18

    From javadoc https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html

    when a static synchronized method is invoked, since a static method is associated with a class, not an object. In this case, the thread acquires the intrinsic lock for the Class object associated with the class. Thus access to class's static fields is controlled by a lock that's distinct from the lock for any instance of the class.

    public static synchronized void getInstance(){}
    

    When we acquire a lock on any class, we actually acquire a lock on "Class" class instance which is only one for all instances of class.

    public synchronized void getInstance(){}
    

    we can create multiple object's of a class and each object will have one lock associated with it.

    0 讨论(0)
提交回复
热议问题