我有一个静态的" Builder"类中的类叫做" MyClass"。如果我尝试从两个线程同时使用构建器创建两个MyClass实例,它会安全吗?可以将一个线程设置的值分配给另一个线程创建的对象吗?
代码:
public class MyClass {
private int height;
private int weight;
private MyClass(Builder builder) {
height = builder.height;
weight = builder.weight;
}
public static class Builder {
private int height;
private int weight;
public Builder height(int h) {
height = h;
return this;
}
public Builder weight(int w) {
weight = w;
return this;
}
public MyClass build() {
return new MyClass(this);
}
}
}
答案 0 :(得分:8)
如果我尝试从两个线程同时使用构建器创建两个MyClass实例,它会安全吗?
如果你的意思是在两个线程中都使用{em>相同的Builder
实例,那么没有,但是如果每个线程都有自己的Builder
实例,那么你就是&#l; ll没事的。有了这种模式:
MyClass c = new MyClass.Builder().height(10).weight(2).build();
每个Builder
实例都是单个线程的本地实例。
答案 1 :(得分:0)
我看到你得到了答案。只是添加它,当然构建器不是线程安全的。在代码的当前形状中,更改为以下内容可能会使其成为
public static class Builder {
private volatile int height;
private volatile int weight;