为什么同步块比同步方法更好? [英] Why is synchronized block better than synchronized method?

查看:21
本文介绍了为什么同步块比同步方法更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始学习线程同步了.

I have started learning synchronization in threading.

同步方式:

public class Counter {

   private static int count = 0;

   public static synchronized int getCount() {
      return count;
   }

   public synchronized setCount(int count) {
      this.count = count;
   }

}

同步块:

public class Singleton {

   private static volatile Singleton _instance;

   public static Singleton getInstance() {
      if (_instance == null) {
         synchronized(Singleton.class) {
            if (_instance == null)
               _instance = new Singleton();
         }
      }
      return _instance;
   }
}

什么时候应该使用 synchronized 方法和 synchronized 块?

When should I use synchronized method and synchronized block?

为什么 synchronized 块比 synchronized 方法更好?

Why is synchronized block better than synchronized method ?

推荐答案

不是更好,只是不同.

当你同步一个方法时,你实际上是在同步到对象本身.在静态方法的情况下,您正在同步到对象的类.所以下面两段代码的执行方式相同:

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() {
    // ...
}

这就像你写的一样.

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

如果您想控制与特定对象的同步,或者您只想将方法的部分同步到该对象,则指定一个 synchronized 块.如果在方法声明中使用 synchronized 关键字,它会将整个方法同步到对象或类.

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.

这篇关于为什么同步块比同步方法更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆