一、privat static Singleton 要加votatile关键字修饰,防止对象的初始化代码与引用赋值代码进行重排序。spa
二、getInstance方法,最外层要加if (instance == null),而后加锁synchronized,而后再加if (instance == null)的判断线程
三、内层if (instance == null) 判断的做用是,若是没有这个内层的判断,多个线程都进入了外层的if (instance == null) 判断,并在锁的地方等待,那么势必会依次建立N个重复的对象,不是单例了。code
示例代码以下:对象
public class Singleton { // 经过volatile关键字的使用,防止编译器将 // 一、初始化对象,二、给对象引用赋值 // 这两步进行重排序 private static volatile Singleton instance = null; private Singleton() { } public static Singleton getInstance() { if (instance == null) { synchronized (instance) { if (instance == null) { instance = new Singleton(); } } } return instance; } }