Java多线程--单例模式

一、饿汉模式

类加载的同时,创建实例

java 复制代码
class Singleton{
    private static Singleton instance new Singleton();
    private Singleton(){}
    public static Singleton getInstance(){
        return instance;
    }
}

二、懒汉模式-单线程版

类加载的时候不创建实例,第一次使用的时候才创建实例

java 复制代码
class Singleton{
    private static Singleton instance = null;
    private Singleton(){}
    public static Singleton getInstance(){
        if(instance == null){
            instance = new Singleton();
        }
        return instance;
    }
}

三、懒汉模式-多线程版

上面的懒汉模式的实现是不安全的

加上synchronized可以改善这里的线程安全问题

java 复制代码
class Singleton{
    private static Singleton instance = null;
    private Singleton(){}
    public synchronized static Singleton getInstance(){
        if(instance == null){
            instance = new Singleton();
        }
        return instance;
    }
}

四、懒汉模式-多线程版(改进)

  • 以下代码在加锁的基础上,做出了进一步的改动
  • 给instance加上volatile
java 复制代码
class Singleton{
    private static volatile Singleton instance = null;
    private Singleton(){}
    public static Singleton getInstance(){
        if(instance == null){
            synchronized(Singleton.calss){
                if(instance == null){
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
相关推荐
benchmark_cc21 分钟前
批量获取量化数据时,如何设置合理的超时和重试机制?——QuantDash 高性能实战指南
开发语言·人工智能·python·pandas·量化·quantdash
2601_9669496522 分钟前
使用 Pandas 读取批量数据时如何避免内存溢出?QuantDash 量化数据工程师避坑指南
开发语言·python·pandas·tushare·akshare·quantdash
郑州光合科技余经理32 分钟前
海外版多语言团购系统架构:主数据互通与核销边界
java·开发语言·前端·后端·系统架构·php·ai编程
ttwuai43 分钟前
Go 后台图片上传到对象存储后,预览 403/404 怎么排查?
开发语言·golang
绿浪19841 小时前
c# 结构体 能不能直接封送检测
开发语言·c#
Jesse_EC1 小时前
为什么我设置的 contentLength 到了消费端变成了 0?
java
vipxieliang1 小时前
ValidX 的 Date 和 DateTime vs JPA 的 Temporal 对比
java·后端
杜touch1 小时前
Spring框架的AnnotationConfigApplicationContext类启动的流程
java
AI人工智能+电脑小能手2 小时前
大白话说Java设计模式-26-策略模式(业务实战篇)
java·spring·设计模式·策略模式·支付系统·算法切换