Java 为什么这个同步方法会给我一个错误?

Java 为什么这个同步方法会给我一个错误?,java,Java,为什么这个方法publicsynchronizedsafe(字符串S)会给我一个编译错误?我知道我们不能同步变量,但上面的代码怎么了 这样的构造函数无法同步: //What will happen when you attempt to compile and run the following code? public class TestThread extends Thread { public static void main(String[] args) {

为什么这个方法publicsynchronizedsafe(字符串S)会给我一个编译错误?我知道我们不能同步变量,但上面的代码怎么了

这样的构造函数无法同步:

//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 + " ");
    }
}
同步构造函数是没有意义的,因为每次调用构造函数时,它都在处理一个单独的新对象。即使两个构造函数同时工作,它也不会发生冲突

指示构造函数上允许哪些can修饰符,并且
synchronized
不是其中之一:

构造函数修改器:

注释公共保护私有

它还指出:

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


没有必要,所以它是不允许的。

您的方法是构造函数,并且不能同步构造函数

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

public Safe(String s) 

你期望它做什么?在构建对象之前,无法共享该对象。
public Safe(String s) {
    str = s;
    str = str.toUpperCase();
    System.out.print(str + " ");
}