<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">最近项目中用到单例在多线程中的应用,和同事们讨论了一下</span>
1、首先介绍一下单例模式
单例模式:确保一个类只有一个实例,而且自行实例化并向整个系统提供这个实例,它提供全局访问的方法。
饿汉式单例类:
public class Singleton {
private static final Singleton singleton = new Singleton();
private Singleton(){
}
public static Singleton getInstance(){
return singleton;
}
}
懒汉式单例类:
public class Singleton {
private static Singleton singleton = null;
private Singleton(){
}
public static Singleton getInstance(){
if(singleton == null){
singleton = new Singleton();
}
return singleton;
}
}
在开发过程中,使用饿汉式单例类,有人可能会考虑饿汉式类一加载就会实例化,提前占用系统资源,所以可能会选择使用懒汉式单例类。
但是懒汉式单例类是线程不安全的,例如两个线程同行调用getInstance方法,并且singleton都为null,这时这两个线程都会创建对象,这样系统中就存在多个单例对象,因而会产生意想不到的bug。
解决懒汉式单例类线程不安全的办法1:使用双重锁定
public class Singleton {
private static Singleton singleton = null;
private Singleton(){
}
public static Singleton getInstance(){
if(singleton == null){
synchronized (Singleton.class) {
if(singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
}
解决懒汉式单例类线程不安全的办法2:使用内部类
public class Singleton {
private Singleton(){
}
private static class SingletonHolder{
private final static Singleton singleton = new Singleton();
}
public static Singleton getInstance(){
return SingletonHolder.singleton;
}
}