单例模式特点:
① 单例类只能有一个实例
② 私有构造方法,不允许通过其他类创建单例类的实例
③ 提供静态get方法返回单实例
饿汉式:类加载的时候就创建实例
懒汉式:类加载时不创建实例,第一次调用get方法时才创建实例
饿汉式优点:简单,调用时速度快,无需考虑创建实例时线程安全问题
饿汉式缺点:占用内存,可能使用该类时只使用了其静态方法,却创建了对象
懒汉式优点:第一次获取实例前占用内存少
懒汉式缺点:需要考虑线程安全,第一次获取实例时要进行初始化工作
饿汉式:
public class SingleInstance1 {
private static final SingleInstance1 instance = new SingleInstance1();
//构造方法要私有
private SingleInstance1() {
System.out.println("SingleInstance1 实例化了一个单例对象");
}
public static SingleInstance1 getInstance() {
return instance;
}
}
volatile 关键字:禁止指令重排序(防止虚拟机先分配地址后初始化对象)、对缓存的修改立即写入主存、阻止其他线程对其进行写操作
双重检查锁定:如果同步块中不再次判断是否为null可能会实例化两次。如果两个线程同时执行完成第一个if,其中一个获得锁并实例化了对象,然后另一个线程进入同步块不会再次判断是否为null,而再次实例化。
懒汉式:使用 synchronized
public class SingleInstance2 {
//使用 volatile 修饰单实例
private volatile static SingleInstance2 instance;
//构造方法要私有
private SingleInstance2() {
}
public static SingleInstance2 getInstance() {
if (instance == null) {
synchronized (SingleInstance2.class) {
if (instance == null) {
instance = new SingleInstance2();
System.out.println("SingleInstance2 实例化了一个单例对象");
}
}
}
return instance;
}
}
懒汉式:使用 ReentrantLock
public class SingleInstance3 {
//使用 volatile 修饰单实例
private volatile static SingleInstance3 instance;
private static ReentrantLock lock = new ReentrantLock();
//构造方法要私有
private SingleInstance3() {
}
public static SingleInstance3 getInstance() {
if (instance == null) {
lock.lock();
try {
if (instance == null) {
instance = new SingleInstance3();
System.out.println("SingleInstance3 实例化了一个单例对象");
}
} finally {
lock.unlock();
}
}
return instance;
}
}



