Java多线程初阶-单例模式的写法 ﹏ヽ暗。殇╰゛Y 2023-09-27 17:11 80阅读 0赞 ## 单例模式 ## 单例模式能保证某个类在程序中只存在唯一一份实例, 而不会创建出多个实例. 单例模式具体的实现方式, 分成 "饿汉" 和 "懒汉" 两种. ## 饿汉模式 ## 类加载的同时, 创建实例. class Singleton { private static Singleton instance = new Singleton(); private Singleton() {} public static Singleton getInstance() { return instance; } } ## 懒汉模式-单线程版 ## 类加载的时候不创建实例. 第一次使用的时候才创建实例 . class Singleton { private static Singleton instance = null; private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } ## 懒汉模式-多线程版 ## 上面的懒汉模式的实现是线程不安全的. > 线程安全问题发生在首次创建实例时. 如果在多个线程中同时调用 getInstance 方法, 就可能导致 创建出多个实例. 一旦实例已经创建好了, 后面再多线程环境调用 getInstance 就不再有线程安全问题了(不再修改 instance 了) 加上 synchronized 可以改善这里的线程安全问题. class Singleton { private static Singleton instance = null; private Singleton() {} public synchronized static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } ## 懒汉模式-多线程版(改进) ## 以下代码在加锁的基础上, 做出了进一步改动: 1.使用双重 if 判定, 降低锁竞争的频率. 2.给 instance 加上了 volatile. > 加锁 / 解锁是一件开销比较高的事情. 而懒汉模式的线程不安全只是发生在首次创建实例的时候. 因此后续使用的时候, 不必再进行加锁了. 外层的 if 就是判定下看当前是否已经把 instance 实例创建出来了. 同时为了避免 "内存可见性" 导致读取的 instance 出现偏差, 于是补充上 volatile . class Singleton { private static volatile Singleton instance = null; private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } } 好了,本期内容就到这里,下期内容更加精彩噢!!
还没有评论,来说两句吧...