单例模式在单线程和多线程中的不同写法

本文介绍了单例模式在不同场景下的实现方式,包括懒汉式、饿汉式以及适用于多线程环境的双重检查加锁法、synchronized修饰方法、急切法和枚举法。探讨了各种方法的优缺点,特别是volatile关键字在多线程中的作用,以确保单例模式的正确实现。

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

单例模式算是一种很常用到的设计模式之一了,今天就来聊一聊在不同场景下如何去实现单例。

单例模式的概念就是:保证一个类只有一个实例,并提供一个访问它的全局访问点。
主要作用呢,就是保证在Java应用程序中,一个类Class只有一个实例存在。

单例模式一般分为 懒汉式 以及 饿汉式。

单例的几种写法:

1.懒汉式(立即加载方式)

public class Singleton {

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

这种写法比较简单,在类加载的时候就完成了实例化,避免了线程同步问题。
但是如果从始至终从未使用过这个实例,则会造成内存的浪费。

2.饿汉式(延迟加载方式)

public class Singleton {

    private static Singleton uniqeInstance = null;
    
    public static Singleton getInstance(){
        if (uniqeInstance == null) {
            uniqeInstance = new Singleton();
        }
        return uniqeInstance;
    }
}

多线程下不可使用该方式,如果线程1执行完if (uniqeInstance == null),还没开始往下执行,线程2也通过了这个判断语句,这时便会产生多个实例。

单例模式在多线程操作时的方式:

3.方法上加synchronized(缺点:消耗过多资源)

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

4.急切法 创建实例多次 (缺点:消耗内存)

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

5.双重检查加锁法(建议使用)

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

注意:这里静态变量中的volatile关键字的作用主要有两个:
1).保证了不同线程对这个变量进行操作时的可见性;
2).禁止了指令重排序
也正是因为这两点,当多个线程操作时,不管到哪一步,只要读到instance的值已改变,则会直接从内存中读取,就不会存在创建多个实例的情况。

6.枚举(用的较少)

public enum SingletonEnum {
    INSTANCE;
    
    public void whateverMethod() {
        
    }
}

借助JDK1.5中添加的枚举来实现单例模式。不仅能避免多线程同步问题,而且还能防止反序列化重新创建新的对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值