多线程环境下的单例模式(懒汉式)

正常情况下的懒汉式

    private static LazySingle instance = null;
    public static LazySingle getInstance() {
        if (instance == null) {
            instance = new LazySingle();
        }
        return instance;
    }

这里很好理解, 如果没有实例对象就创建一个, 如果已经存在该实例对象, 就直接返回该对象.

但这在多线程环境下会有线程安全问题, 比如线程A和B同时去调用getInstance()方法, 由于没有队列关系, 两个线程同时认为没有实例对象存在, 这样最终会导致两个线程分别创建了一个对象.

package singletest;

/**
 * @Date:2022/1/8 9:56
 * @Author:NANDI_GUO
 */
public class LazySingle {
    private int count;

    private LazySingle() {
        count++;
        System.out.println(Thread.currentThread().getName()+"创建了对象"+count+"次");
    }

    private static LazySingle instance = null;

    public static LazySingle getInstance() {
        if (instance == null) {
            instance = new LazySingle();
        }
        return instance;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 2; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    LazySingle.getInstance();
                }
            }).start();
        }
    }
}
============================================================
输出:
Thread-0创建了对象1Thread-1创建了对象1
解决办法1, 在实例化的getInstance()方法上加锁
    private static LazySingle instance = null;
    public static synchronized LazySingle getInstance() {
        if (instance == null) {
            instance = new LazySingle();
        }
        return instance;
    }
=================================================
输出:
Thread-0创建了对象1

但这样的话, 极大的影响了运行效率. 所有线程在进入该方法时都需要排队等锁了

解决办法2, 双检索模式
private static LazySingle instance = null;

    public static volatile LazySingle getInstance() {
        if (instance == null) {
            synchronized(LazySingle.class) {
                if (instance == null) {
                    instance = new LazySingle();
                }
            }
        }
        return instance;
    }

主要是, 两次判空, 所有线程判空之后,排队等待获得锁, 只要有一个线程获得锁后, instance就不再为空, 那么剩下在等待的线程就不再会等待锁,直接结束了.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rimumu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值