【问题标题】:why does this synchronized method give me an error? [duplicate]为什么这个同步方法会给我一个错误? [复制]
【发布时间】:2015-03-19 07:29:11
【问题描述】:
//What will happen when you attempt to compile and run the following code?

public class TestThread extends Thread {
    public static void main(String[] args) {
        new TestThread().start();
        new TestThread().start();
    }

    public void run() {
        Safe s1 = new Safe("abc");
        Safe s2 = new Safe("xyz");
    }
}

class Safe {
    String  str;

    public synchronized Safe(String s) {
        str = s;
        str = str.toUpperCase();
        System.out.print(str + " ");
    }
}

为什么这个方法 public synchronized Safe (String S) 给我一个编译错误?我知道我们不能同步变量但是上面的代码有什么问题?!?!

【问题讨论】:

  • 你希望它做什么?在构建之前,您不能共享对象。

标签: java


【解决方案1】:

这样的构造函数不能同步:

public Safe(String s) 

synchronize 构造函数没有意义,因为每次调用构造函数时,它都在处理一个单独的新对象。即使两个构造函数同时工作,也不能冲突。

Section 8.8.3 of the JLS 表示可以在构造函数上使用什么修饰符,synchronized 不是其中之一:

构造器修饰符:

注释公共保护私有

另外,它指出:

实际上没有必要同步构造函数,因为它会锁定正在构造的对象,在对象的所有构造函数完成工作之前,其他线程通常无法使用该对象。

没有必要,所以不允许。

【讨论】:

    【解决方案2】:

    你的方法是构造函数,构造函数不能同步。

    请参考this question

    【讨论】:

      【解决方案3】:

      构造函数(据我所知)无法同步。因为当您调用构造函数时,它会在内存中创建一个新位置。这个新位置在创建之前不能有 2 个以上的东西试图同时访问它,因此不需要同步构造函数。你的方法应该是:

      public Safe(String s) {
          str = s;
          str = str.toUpperCase();
          System.out.print(str + " ");
      }
      

      【讨论】:

        猜你喜欢
        • 2014-08-31
        • 1970-01-01
        • 2013-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多