当前位置: 首页 > news >正文

多线程下单例如何保证

系列文章目录

文章目录

  • 系列文章目录
  • 一、方法
    • 1、懒汉式+双重检查锁
    • 2、饿汉式静态初始化
    • 3、使用静态内部类(懒汉式的一种变体)
    • 4、使用 AtomicReference
    • 5、使用依赖注入框架,Spring


一、方法


懒汉式:延迟加载,第一次调用getInstance()才能创建对象
饿汉式:立即加载,类加载时就创建对象

1、懒汉式+双重检查锁

package com.example.demo;public class SingleTest {private static volatile SingleTest instance;private SingleTest(){}private static SingleTest getInstance() {if (instance == null) {synchronized (SingleTest.class) {if (instance == null) {instance = new SingleTest();}}}return instance;}public static void main(String[] args) {new Thread(() -> {SingleTest singleTest1 = SingleTest.getInstance();System.out.println("singleTest1: " + singleTest1);}).start();new Thread(() -> {SingleTest singleTest2 = SingleTest.getInstance();System.out.println("singleTest2: " + singleTest2);}).start();new Thread(() -> {SingleTest singleTest3 = SingleTest.getInstance();System.out.println("singleTest3: " + singleTest3);}).start();}
}

2、饿汉式静态初始化

public class Singleton {private static final Singleton instance = new Singleton();private Singleton() {}public static Singleton getInstance() {return instance;}
}

3、使用静态内部类(懒汉式的一种变体)

public class Singleton {private Singleton() {}private static class SingletonHolder {private static final Singleton instance = new Singleton();}public static Singleton getInstance() {return SingletonHolder.instance;}
}

4、使用 AtomicReference

import java.util.concurrent.atomic.AtomicReference;public class Singleton {private static final AtomicReference<Singleton> INSTANCE = new AtomicReference<>();private Singleton() {}public static Singleton getInstance() {for (;;) {Singleton current = INSTANCE.get();if (current != null) {return current;}Singleton newInstance = new Singleton();if (INSTANCE.compareAndSet(null, newInstance)) {return newInstance;}}}
}

5、使用依赖注入框架,Spring

@Component
public class MyService {// ...
}
http://www.dtcms.com/a/348965.html

相关文章:

  • [身份验证脚手架] 前端认证与个人资料界面
  • 2025.8.18-2025.8.24第34周:有内耗有挣扎
  • Spring Cloud 快速通关之Sentinel
  • 遥感机器学习入门实战教程|Sklearn案例⑩:降维与分解(decomposition 模块)
  • [e3nn] 等变神经网络 | 线性层o3.Linear | 非线性nn.Gate
  • 动态规划--编译距离
  • AI代码生成器全面评测:六个月、500小时测试揭示最强开发助手
  • Redis 高可用篇
  • 51单片机-实现定时器模块教程
  • GaussDB 数据库架构师修炼(十八) SQL引擎-统计信息
  • 用 WideSearch 思路打造「零幻觉、全覆盖」的多 Agent 信息收集器
  • SRE 系列(四)| MTTI 与 On-Call:高效故障响应之道
  • C++标准库算法:从零基础到精通
  • Go语言 Hello World 实例
  • 数据标注的质检环节有多少种
  • 单表查询-分析函数的应用
  • 智能体之推理引擎(3)
  • 记一次使用 C++ 实现多种扑克牌逻辑
  • ptrade `get_fundamentals` - 获取财务数据
  • 58 C++ 现代C++编程艺术7-模板友元
  • VC2022连接mysql
  • 微服务-21.网关路由-路由属性
  • 2025年KBS SCI1区TOP,新颖奖励与ε-贪婪衰减Q-learning算法+局部移动机器人路径规划,深度解析+性能实测
  • AI基础学习周报十
  • AI产品经理面试宝典第74天:技术边界与商业闭环的面试问题与答法
  • Trip Footprint_旅行分享功能模块技术架构天气模块技术架构
  • COSMIC智能化编写工具:革命性提升软件文档生成效率
  • 【文献阅读】Land degradation drivers of anthropogenic sand and dust storms
  • docker安装及常用命令
  • 卷王问卷考试系统—测试报告