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

jht*_*jht 0 java

//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 + " ");
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么这个方法公共同步安全(String S)给我一个编译错误?我知道我们无法同步变量,但上面的代码出了什么问题?!?!

rge*_*man 8

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

public Safe(String s) 
Run Code Online (Sandbox Code Playgroud)

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

JLS的第8.8.3节指出了构造函数允许的修饰符,而synchronized不是其中之一:

ConstructorModifier:

注释公共保护私人

此外,它指出:

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

没有必要,所以不允许.