Why is synchronized block better than synchronized method?

后端 未结 10 983
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:33

    It's not a matter of better, just different.

    When you synchronize a method, you are effectively synchronizing to the object itself. In the case of a static method, you're synchronizing to the class of the object. So the following two pieces of code execute the same way:

    public synchronized int getCount() {
        // ...
    }
    

    This is just like you wrote this.

    public int getCount() {
        synchronized (this) {
            // ...
        }
    }
    

    If you want to control synchronization to a specific object, or you only want part of a method to be synchronized to the object, then specify a synchronized block. If you use the synchronized keyword on the method declaration, it will synchronize the whole method to the object or class.

提交回复
热议问题