单例模式第一版:
public class Singleton { //单例对象 private static Singleton ourInstance = null; //静态工厂方法 public static Singleton getInstance() { if(ourInstance == null){ ourInstance = new Singleton(); } return ourInstance; } //私有构造函数 private Singleton() { } }
为什么要这样写?
1.要想让一个类只能构建一个对象,自然不能让它随便去做new 操作,因此Signleton的构造方法是私有的。
2.ourstance是Singleton类的静态成员,也是我们的单例对象。它的初始值可以写成null,也可以写成new Singleton().至少其中的区别后来解释
2.getInstance是获取单例对象的方法
如果单例初始值为null,还未构建,则构建单例对象并未返回。这个写法属于单例模式当中的懒汉模式
如果单例对象一开始就被new Singleton()主动构建,则不再需要判空操作,这种写法属于饿汉模式
饿汉:主动找食物吃。懒汉:躺在地上等着人喂
3.刚才的代码非线程安全
单例模式第二版
public class Singleton { //单例对象 private static Singleton ourInstance = null; //静态工厂方法 public static Singleton getInstance() { if(ourInstance == null){ synchronized (Singleton.class){if(ourInstance == null){ourInstance = new Singleton();} } } return ourInstance; } //私有构造函数 private Singleton() { } }1.为了防止new Singleton被执行多次,因此在new操作之前加上synchorized同步锁,锁住整个类
2.进入synchorized临界区以后,还要在做一次判空,因为当两个线程同时访问的时候,线程A构建完对象,线程B也已经通过了最初的判空验证,不做第二次判空,线程B还会再次构建ourstance对象
两次判空的机制叫双重检测机制
单例模式第三版
public class Singleton { //单例对象 private volatile static Singleton ourInstance = null; //静态工厂方法 public static Singleton getInstance() { if(ourInstance == null){ synchronized (Singleton.class){ ourInstance = new Singleton(); } } return ourInstance; } //私有构造函数 private Singleton() { } }1.经过volatile的修饰,当线程A执行ourstance = new Singleton的时候,JVM执行顺序memory = allocate();分配对象的内存
ctorourstance(memory);初始化对象
ourstance = memory;设置ourstance指向刚分配的内存地址
2.volatile关键字不但可以防止指令重排。也可以保证线程访问的变量值是在主内存中的最新值