标签:单例模式
1、懒汉式(线程不安全)
public class Singleton { private static Singleton instance; private Singleton (){} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
2、懒汉式(线程安全)
public class Singleton { private static Singleton instance; private Singleton (){} public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }3、饿汉式(静态内部类实现lazy loading)
public class Singleton { private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } private Singleton (){} public static final Singleton getInstance() { return SingletonHolder.INSTANCE; } }
4、双重校检锁
public class Singleton { private volatile static Singleton singleton; private Singleton (){} public static Singleton getSingleton() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }
双重校检机制的实现会使用一个关键字volatile,这个关键字的意思是:被volatile修饰的变量的值,将不会被本地线程所缓存,所有对本变量的读写都是直接操作共享内存的,从而确保多个线程可以正确的处理该变量。
标签:单例模式
原文地址:http://blog.csdn.net/ivyvae/article/details/41079069