单例模式
单个实例,只能new一次
恶汉
一上来直接给
如果他不需要,岂不是浪费资源⊙﹏⊙‖∣°
/** 第一步: 不能给别人new **/
private EntitySingleton() {
}
/** 恶汉 **/
static EntitySingleton instance = new EntitySingleton();
public static EntitySingleton getInstance() {
return instance;
}
懒汉
向你要了再给
/*
* 为什么不使用同步方法(‧_‧?)
* synchronized两个模式 开,关-->耗时!!!
*
* 1.synchronized 解决线程安全问题
*
* 2.多一个if 解决效率问题
*/
public static EntitySingleton getInstance2() {
if (instance2 == null) {// 解决效率问题
//如果没有这层判断,则与同步方法无异
synchronized (EntitySingleton.class) {
if (instance2 == null) {//当线程一new了一次后
//线程二无法再new
// 单个实例,只能new一次!!
try {
Thread.sleep(100);// 模拟cpu调度 , 线程安全
} catch (InterruptedException e) {
e.printStackTrace();
}
instance2 = new EntitySingleton();
}
}
}
return instance2;
}