问题描述
- getInstance有不是单例的情况吗
- private static DeviceServerHolder instance = null;
public static DeviceServerHolder getInstance() {
if (instance == null) {
instance = new DeviceServerHolder();
}
return instance;
}
我在两个方法里调用getInstance()方法。方法A检测到instance是空,建了一个新的实例a。方法B检测到instance是空,又建了一个新的实例b。此后A再调用getInstance()方法时全用实例a,B再调用getInstance()方法时全用实例b。
不明白这是为什么,跪求各位指点指点。。其中A方法是在rmi接口的实现类中
解决方案
解决方案二:
单例实现要考虑多线程
public static DeviceServerHolder getInstance() {
synchronized(this) {
if (instance == null) {
instance = new DeviceServerHolder();
}
return instance;
}
}
解决方案三:
多线程的情况,当A,B,,2个线程同时访问getInstance的时候,instance就都为空,,就会创建2个实例而不是单例了,,改成public synchronized static......
时间: 2024-08-04 09:37:41