设计模式之懒汉单例非线程安全

本文通过一个Java示例程序详细介绍了懒汉式单例模式的实现方式及其非线程安全的问题。通过创建多个线程尝试获取单例对象来展示这种实现方式可能导致的问题。
package design.singletonLazy.demo;

public class Main {

    public static void main(String[] args) {
        // 创建多线程验证
        Thread t1 = new Thread() {
            @Override
            public void run() {
                SingletonLazyUnsafetyEntity s = SingletonLazyUnsafetyEntity.getSingletonEntity();
                System.out.println("t1线程获取对象的hashcode: " + s.hashCode());
            }
        };
        Thread t2 = new Thread() {
            @Override
            public void run() {
                SingletonLazyUnsafetyEntity s = SingletonLazyUnsafetyEntity.getSingletonEntity();
                System.out.println("t2线程获取对象的hashcode: " + s.hashCode());
            }
        };
        Thread t3 = new Thread() {
            @Override
            public void run() {
                SingletonLazyUnsafetyEntity s = SingletonLazyUnsafetyEntity.getSingletonEntity();
                System.out.println("t3线程获取对象的hashcode: " + s.hashCode());
            }
        };
        t1.start();
        t2.start();
        t3.start();
    }

}
//如果相同则多启动几次试试
// t1线程获取对象的hashcode: 475341210
// t2线程获取对象的hashcode: 162086129
// t3线程获取对象的hashcode: 162086129
package design.singletonLazy.demo;

//懒汉式单例-非线程安全
public class SingletonLazyUnsafetyEntity {

    // 直接创建对象实例
    private static SingletonLazyUnsafetyEntity s = null;

    // 实例输出出口
    public static SingletonLazyUnsafetyEntity getSingletonEntity() {
        if (s == null) {
            s = new SingletonLazyUnsafetyEntity();
        }
        return s;
    }

    // 私有化构造方法,让外部无法通过new创建
    private SingletonLazyUnsafetyEntity() {

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值