一、饿汉式
public class Hungry {
private Hungry(){
}
private static Hungry hungry = new Hungry();
public static Hungry getInstance(){
return hungry;
}
}
优点:不会存在线程安全的问题
缺点:占据内存
二、懒汉式
public class Lazy {
private Lazy(){
}
private volatile static Lazy lazy;//保证其原子性,禁止指令重排序
public static Lazy getInstance(){
if(lazy==null){
synchronized (Lazy.class) {
if(lazy==null){
lazy = new Lazy();
/*
* 1.分配地址空间
* 2.调用构造方法
* 3.将对象指向分配的地址空间
*
* 可能指令重排序:132
* */
}
}
}
return lazy;
}
}
优点:不会占据多余的内存
缺点:会产生一系列的线程安全问题,需要一一对应修改代码
1510

被折叠的 条评论
为什么被折叠?



