1、双重锁检查(DCL)单例模式
public class Singleton { private static volatile Singleton instance = null;//防止指令重排序,拿到半成品对象 private Singleton() {} public static Singleton getInstance() { if(null == instance) {//避免每次都进行锁竞争,提高执行效率 synchronized(Singleton.class) {//加锁 if(null == instance) {//防止多个线程越过第一个if后多次创建对象 instance = new Singleton(); } } } return instance; } }
2、静态内部类单例
public class Singleton { private Singleton() {} pirvate static class SingletonHolder { public final static Singleton instance = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.instance; } }