【问题标题】:How a static synchronized function works? [duplicate]静态同步函数如何工作? [复制]
【发布时间】:2013-07-14 04:23:28
【问题描述】:

当 Java 成员需要是线程安全的时,我们执行以下操作:

 public synchronized void func() {
     ...
 }

这个语法相当于:

 public void func() {
      synchronized(this) {
           ....
      }
 }

也就是说,它实际上使用this作为锁。

我的问题是,如果我使用synchronizedstatic 方法,如下:

class AA {
    private AA() {}

    public static synchronized AA getInstance() {
        static AA obj = new AA();
        return obj;
    }
}

在这种情况下,synchronized 方法的锁定是什么?

【问题讨论】:

  • AA类将被锁定synchronized(AA.class),但没有实例
  • 局部变量obj的静态声明不是语法错误吗?

标签: java thread-safety synchronized


【解决方案1】:

在静态同步方法的情况下,class AAclass 对象将是隐式锁定

相当于

class AA {
    private AA() {}

    public static AA getInstance() {
        synchronized(AA.class) {
           AA obj = new AA();
           return obj;
        }
    }
}

【讨论】:

  • +1。相当于synchronized (AA.class) {
  • 但是static AA obj = new AA(); 呢?它不会给出编译时错误吗?
  • 感谢@Bingo 我现在已经更正了。我没有注意那个代码
  • @sanbhat 很好,但你当然值得 +1 投票
  • @sanbhat 所以当我们在this 上同步时,另一个对象不能执行同步线程,但是当在类上同步时呢?究竟会发生什么?确实它获得了类的锁;这是否意味着另一个类无法执行同步的代码?
【解决方案2】:

来自section 8.4.3.6 of the JLS

同步方法在执行之前获取监视器(第 17.1 节)。

对于类(静态)方法,使用与该方法的类的 Class 对象关联的监视器。

因此,您的代码获取了AA.class 的监视器。正如sanbhat所说,就像

synchronized(AA.class) {
    ...
}

...就像使用实例方法一样

synchronized(this) {
    ...
}

【讨论】:

    【解决方案3】:

    它适用于 AA.class 锁。

    public static AA getInstance() {
            synchronized(AA.class){
                static AA obj = new AA();
                return obj;
            }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2012-06-21
      • 2014-06-30
      • 1970-01-01
      • 1970-01-01
      • 2011-07-10
      • 2011-09-20
      • 2012-03-13
      • 2020-07-13
      • 1970-01-01
      相关资源
      最近更新 更多