![](/img/trans.png)
[英]Synchronization between two threads using same and different instance of class?
[英]What is the problem with using an instance of the following class to share between threads?
有人问我使用以下类的实例在线程之间共享有什么问题。 有哪些风险? 什么是可能的解决方案?
public class States {
private String[] states = new String[] {
"UNK", "NEW", "RUNNING", "DONE"
};
public String[] getStates() {
return states;
}
}
这段代码的问题在于,尽管数组在 Java 中是不可变的,但是因为您公开了对数组的引用,所以没有什么可以阻止任何人用新数组重新分配整个数组。 对于此用例,最好使用枚举类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.