EffectiveJava-单例

本文详细介绍了Java中的单例模式,包括懒汉式和饿汉式的实现方式。懒汉式在多线程环境下可能出现线程不安全问题,而饿汉式则确保了线程安全但提前初始化了实例。通过示例代码展示了两种模式的优缺点,强调了线程安全在单例模式中的重要性。

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

使用场景

• 程序运行只需要一个类的实例
• 需要频繁创建和销毁的对象
• 创建对象时消耗时间过多,但又经常用到的对象

单例的必要条件

• 构造器私有化
• 实例必须是一个且唯一,并且必须加上static属性
• 统一由一个静态方法供外界获取单例

两种实现模式

懒汉单例

可理解为懒加载模式,在使用的时候才会实例化。
但是会有问题,如果多线程访问,会线程不安全

public class Test {

    private Test() {

    }

    private static Test instance;

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

所以多线程使用懒汉模式的时候要考虑线程安全

public static void main(String[] args) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                Test instance = Test.getInstance();
                System.out.println(instance);
            }
        };
        thread.start();
        Test instance = Test.getInstance();
        System.out.println(instance);
    }

lesson3.Test@a09ee92
lesson3.Test@7d77bb0a

可以看到输出的类并非单例,而是存在多个实例
所以如果懒汉要有多线程访问要用线程锁

public class Test {

    private Test() {

    }

    private Integer age;

    private static Test instance;

    public static Test getInstance() {
        if (instance == null) {
            synchronized (Test.class) {
                if (instance == null) {
                    instance = new Test();
                }
            }
            instance = new Test();
        }
        return instance;
    }
}
饿汉单例
public class Test {

    private Test() {

    }

    private static final Test INSTANCE = new Test();

    public static Test getInstance() {
        return INSTANCE;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值