单例模式,有“懒汉式”和“饿汉式”两种。安全
懒汉式多线程
单例类的实例在第一次被引用时候才被初始化。性能
public class Singleton { private static Singleton instance=null; private Singleton() { } public static Singleton getInstance(){ if (instance == null) { instance = new Singleton(); } return instance; } }
饿汉式this
单例类的实例在加载的时候就被初始化。线程
public class Singleton { private static Singleton instance = new Singleton(); private Singleton() { } public static Singleton getInstance(){ return instance; } }
在单线程程序中,上面两种形式基本能够知足要求了,可是在多线程环境下,单例类就有可能会失效,这个时候就要对其加锁了,来确保线程安全。code
对线程加锁用的synchronized关键字,这个关键字的用法主要也分为两种:对象
一种是加在方法名以前,形如:synchronized methodeName(params){……};blog
二是声明同步块,形如:synchronized(this){……};get
下面是对懒汉式单例类加上线程同步的实现:同步
同步方法:
public class Singleton { private static Singleton instance=null; private Singleton() { } public synchronized static Singleton getInstance(){ if (instance == null) { instance = new Singleton(); } return instance; } }
这种方式效率比较低,性能不是太好,不过也能够用,由于是对整个方法加上了线程同步,其实只要在new的时候考虑线程同步就好了,这种方法不推荐使用。
同步代码块:
public class Singleton { private static Singleton instance; private final static Object syncLock = new Object(); private Singleton() { } public static Singleton getInstance(){ if (instance == null) { synchronized (syncLock) { if (instance == null) { instance = new Singleton(); } } } return instance; } }
synchronized同步块括号中的锁定对象是采用的一个无关的Object类实例,而不是采用this,由于getInstance是一个静态方法,在它内部不能使用未静态的或者未实例的类对象,所以也能够用下面的方法来实现:
public class Singleton { private static Singleton instance; private Singleton() { } public static Singleton getInstance(){ if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } }