本文共 3139 字,大约阅读时间需要 10 分钟。
1、单例类有且只有一个实例。 2、单例类必须只能自己创建自己的唯一实例 (构造函数私有)。 3、单例类必须能给所有其他对象提供这一实例(提供获取实例的方法)。
public class Singleton { private static Singleton instance; private Singleton (){ } public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
public class Singleton { private static Singleton instance; private Singleton (){ } public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
public class Singleton { private static Singleton instance; private Singleton (){ } public static Singleton getInstance() { // 使用synchronized 块,临界资源的同步互斥访问 synchronized(Singleton.class){ if (instance == null) { instance = new Singleton(); } } return instance; } }
public class Singleton { //使用volatile关键字防止重排序,因为 new Instance()是一个非原子操作,可能创建一个不完整的实例 private static volatile Singleton instance; private Singleton (){ } public static Singleton getInstance() { if (instance == null) { synchronized(Singleton.class){ // 使用synchronized 块,临界资源的同步互斥访问 if (instance == null) { instance = new Singleton(); } } } return instance; } }
// 线程安全的懒汉式单例public class Singleton { // 私有内部类,按需加载,用时加载,也就是延迟加载 private static class Holder { private static Singleton singleton = new Singleton(); } private Singleton() { } public static Singleton getSingleton() { return Holder.singleton; }
volatile:
当一个共享变量被volatile修饰时,它会保证修改的值会立即被更新到主存,当有其他线程需要读取时,它会去内存中读取新值。public class Singleton { // ThreadLocal 线程局部变量,将单例instance线程私有化 private static ThreadLocalthreadlocal = new ThreadLocal (); private static Singleton instance; private Singleton() { } public static Singleton getInstance() { // 第一次检查:若线程第一次访问,则进入if语句块;否则,若线程已经访问过,则直接返回ThreadLocal中的值 if (threadlocal.get() == null) { synchronized (Singleton.class) { if (instance == null) { // 第二次检查:该单例是否被创建 instance = new Singleton(); } } threadlocal.set(instance); // 将单例放入ThreadLocal中 } return threadlocal.get(); }}
:
public class Singleton { private static Singleton instance = new Singleton(); private Singleton (){ } public static Singleton getInstance() { return instance; } }优点: 没有加锁,执行效率会提高; 缺点:类加载时就初始化,浪费内存。
转载地址:http://ohagj.baihongyu.com/