DLC需要加volatile吗?

本文探讨了在实现双重检查的单例模式时为何需要使用volatile关键字。内容包括单例模式的创建过程,强调了volatile在并发编程中的作用,确保多线程环境下对实例的正确访问。
摘要由CSDN通过智能技术生成
Test test = new Test();
  • 创建过程
  • 1.申请内存 成员变量赋默认值
  • 2.调用构造方法 初始化成员变量
  • 3.test建立指引

下面重点来了

public class Test {

    /**
     * 单例模式
     */
    //首先私有化构造方法
    private Test(){}

    private static volatile Test test;
    public static Test getInstance(){
        if(test == null){//外部这个判断主要是为了效率
            synchronized (Test.class){//保证原子性 可见性
                if(test == null){
                    try {
                        Thread.sleep(1);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    test = new Test();
                }
            }
        }
        return test;
    }


    public static void main(String[] args) {
        Test test = new Test();

        for(int i = 0;i < 100;i++){
            new Thread(()->{
                System.ou
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值