暗中观察

Java单例模式的三种实现方式
单例模式之饿汉式//饿汉式 public class Singleton1 { private Singlet...
扫描右侧二维码阅读全文
10
2018/09

Java单例模式的三种实现方式

单例模式之饿汉式

//饿汉式
public class Singleton1 {
  private Singleton1() {
}
private static Singleton1 instance = new Singleton1();

public static Singleton1 getInstance(){
    return instance;
}

}

单例模式之懒汉式

//懒汉式、支持多并发、效率低
public class Singleton3 {
    private Singleton3() {
    }
    private static Singleton3 instance = null;
    public synchronized static Singleton3 getInstance(){
        if (instance == null){
            instance = new Singleton3();
        }
        return instance;
    }

}

单例模式之双锁式

//double checked locking、支持多并发、效率高、添加volatile关键字
public class Singleton4 {
    private Singleton4() {
    }
    private volatile static Singleton4 instance = null;
    public static Singleton4 getInstance(){
        if (instance == null){//1
            synchronized (Singleton4.class) {
                if (instance == null)//2
                    instance = new Singleton4();
            }
        }
        return instance;
    }
}
Last modification:April 4th, 2019 at 01:32 am
If you think my article is useful to you, please feel free to appreciate

Leave a Comment