-
12345678910111213
/** * 饿汉式单例 */public class Singleton1 { // 静态成员变量,在静态初始化时便实例化对象 private static final Singleton1 singleton = new Singleton1(); // 构造私有 private Singleton1(){ } public static Singleton1 getSingletonInstance(){ return singleton; }}
1234567891011121314
/** * 懒汉式单例(synchronized关键字线程安全) */public class Singleton3 { private static Singleton3 singleton; private Singleton3(){} // 获取实例 public static synchronized Singleton3 getSingletonInstance(){ if(singleton == null){ singleton = new Singleton3(); } return singleton; }}
1234567891011121314151617181920212223
/** * 双重校验锁(double-checked locking,DCL) */public class Singleton4 { /** * 成员变量这里会加上关键字 volatile,目的是为了防止指令重排序 */ private static volatile Singleton4 singleton; private Singleton4(){} // 获取实例 public static Singleton4 getSingletonInstance(){ // 第一次校验,没有实例化才进入同步代码块 if(singleton == null){ synchronized (Singleton4.class){ // 进入同步代码块后,再判断,如果为空才创建实例 if(singleton == null){ singleton = new Singleton4(); } } } return singleton; }}
123456789101112131415161718
/** * 静态内部类 */public class Singleton5 { private Singleton5(){} // 获取实例 public static Singleton5 getSingletonInstance(){ return SingletonHolder.SINGLETON; } /** * 内部类,JVM在类加载的时候,是互斥的,可以保证线程安全 */ private static class SingletonHolder{ private static final Singleton5 SINGLETON = new Singleton5(); }}
/** * 枚举方式 */public enum Singleton6 { /** * 枚举方式实现单例 */ SINGLETON; public void handle() { // to do something }}
Update your browser to view this website correctly. Update my browser now
×