java中常用设计模式之单例模式之懒汉模式

博客介绍了懒加载模式,即延迟加载,真正使用时才实例化。但并发时可能破坏单实例,需加锁。加锁位置不同有不同问题,如方法前加锁影响效率,延迟加锁可能因指令重排导致空指针。设计时要注意线程安全、优化锁和禁止指令重排等问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

懒加载模式
延迟加载,只有真正使用的时候才会实例化。

package lazysingleton;

public class LazySingLetonTest {
    public static void main(String[] args) {
        myThread myThread = new myThread();
        Thread thread = new Thread(myThread);
        thread.start();
        myThread myThread1 = new myThread();
        Thread thread1 = new Thread(myThread1);
        thread1.start();

    }
}

class LazySingLeton {
    private static LazySingLeton instance;

    public LazySingLeton() {
    }

    public static LazySingLeton getInstance() throws InterruptedException {
        if (instance == null)
            try {
                Thread.sleep(200);
            } catch (Exception e) {
                e.printStackTrace();
            }
        {
            instance = new LazySingLeton();
        }
        return instance;

    }
}

class myThread extends Thread {
    @Override
    public void run() {
        LazySingLeton lazySingLeton = null;
        try {
            lazySingLeton = LazySingLeton.getInstance();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(lazySingLeton);
    }
}

这样设计时当发生并发时,同时有两个线程进入这个地方,那么也就破坏了只有一个实例的初衷,在这里插入图片描述
所以我们要加锁。。。。。。
加锁位置可以是
在这里插入图片描述

在方法前加锁(但是很影响执行效率)
在这里插入图片描述
然后我们加锁的位置延迟(此时可能发生两个线程同时进入,第一个线程指令重排后先引用赋值,但是还没有进行初始化,那么第二个线程拿到了一个空指针。)
在这里插入图片描述
此时我们应该禁止指令重排
在这里插入图片描述
所以在设计时要注意这些地方
1,线程安全
2,优化锁
3,指令重排等问题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值