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

后端 未结 23 2339
北荒
北荒 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 05:11

    Synchronized methods can be checked using reflection API. This can be useful for testing some contracts, such as all methods in model are synchronized.

    The following snippet prints all the synchronized methods of Hashtable:

    for (Method m : Hashtable.class.getMethods()) {
            if (Modifier.isSynchronized(m.getModifiers())) {
                System.out.println(m);
            }
    }
    

提交回复
热议问题