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

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

问题描述

我已开始在线程中学习同步。

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;
}

我应该何时使用同步方法和同步块?
为什么同步块比同步方法更好?

When should I use Synchronized method and Synchronized block ? 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.

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

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