2015-01-20 82 views
0
//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 + " "); 
    } 
} 

为什么这个方法公开同步安全(字符串S)给我一个编译错误?我知道我们不能同步变量,但是上面的代码有什么问题?!?!为什么这种同步方法给我一个错误?

+0

你期望它做什么?在构建完成之前,您无法共享对象。 – 2015-01-20 22:24:40

回答

8

构造像这样不能同步:

public Safe(String s) 

这是没有意义的synchronize一个构造函数,因为每一个构造函数被调用时,它正在一个独立的,新的对象。即使两个构造函数同时工作,它也不会发生冲突。

Section 8.8.3 of the JLS指明了可以修改器允许在一个构造函数,​​是不是其中之一:

ConstructorModifier:

注释公众保护私人

而且,它规定:

T这里没有实际的需要同步构造函数,因为它会锁定正在构建的对象,在对象的所有构造函数完成其工作之前,这些对象通常不会被其他线程使用。

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

1

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

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