public class Singleton { private volatile static Singleton singleton; private Singleton() { } public Singleton getInstance() { if (null == singleton) { synchronized (Singleton.class) { if (null == singleton) { singleton = new Singleton(); } } } return singleton; } }
使用double check保证实例只初始化一次,使用volatile保证不会因为指令重排造成错误