我在名为“MyClass”的类中有一个静态“Builder”类。如果我尝试从两个线程同时使用构建器创建 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);
}
}
}
最佳答案
If I try to create two instances of MyClass using the builder simultaneously from two threads, will it be safe?
如果您的意思是在两个线程中使用 相同 Builder
实例,则否,但如果每个线程都有自己的 Builder
实例那么你会没事的。使用这种模式:
MyClass c = new MyClass.Builder().height(10).weight(2).build();
每个 Builder
实例对于单个线程都是本地的。
关于java - 静态嵌套类线程安全 - java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24587908/