Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

后端 未结 23 2011
北荒
北荒 2020-11-22 04:29

Can any one tell me the advantage of synchronized method over synchronized block with an example?

23条回答
  •  自闭症患者
    2020-11-22 04:46

    In case of synchronized methods, lock will be acquired on an Object. But if you go with synchronized block you have an option to specify an object on which the lock will be acquired.

    Example :

        Class Example {
        String test = "abc";
        // lock will be acquired on String  test object.
        synchronized (test) {
            // do something
        }
    
       lock will be acquired on Example Object
       public synchronized void testMethod() {
         // do some thing
       } 
    
       }
    

提交回复
热议问题