public class Singleton {
    private volatile static Singleton singleton;

    private Singleton() {}

    public static Singleton getInstance() {
        if (singleton == null) {
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}

注释:

  1. volatile 关键字保证了多线程环境下的可见性和有序性,即在一个线程中修改了 singleton 的值后,其他线程能够立即看到这个修改。
  2. 双重校验锁的主要思想是在锁的基础上,再加上一层判断,以减少锁的使用,提高程序的性能。第一层判断是为了避免重复创建对象,第二层判断是为了避免多个线程同时进入锁里面创建对象。
单例双重校验-java-代码

原文地址: http://www.cveoy.top/t/topic/qV1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录