Why is synchronized block better than synchronized method?

后端 未结 10 982
Happy的楠姐
Happy的楠姐 2020-12-07 08:05

I have started learning synchronization in threading.

Synchronized method:

public class Counter {

   private static int count = 0;

   public stati         


        
10条回答
  •  我在风中等你
    2020-12-07 08:27

    The difference is in which lock is being acquired:

    • synchronized method acquires a lock on the whole object. This means no other thread can use any synchronized method in the whole object while the method is being run by one thread.

    • synchronized blocks acquires a lock in the object between parentheses after the synchronized keyword. Meaning no other thread can acquire a lock on the locked object until the synchronized block exits.

    So if you want to lock the whole object, use a synchronized method. If you want to keep other parts of the object accessible to other threads, use synchronized block.

    If you choose the locked object carefully, synchronized blocks will lead to less contention, because the whole object/class is not blocked.

    This applies similarly to static methods: a synchronized static method will acquire a lock in the whole class object, while a synchronized block inside a static method will acquire a lock in the object between parentheses.

提交回复
热议问题