Java单例7种测试实践

单例:一个进程中只能存在唯一一个对象。

1.饿汉模式。 主动型太粗暴。


/**
 * @author :jiaolian
 * @date :Created in 2021-01-10 21:25
 * @description:饿汉单例测试
 * @modified By:
 * 公众号:叫练
 */
public class HungerSignletonTest {
    //类初始化会创建单例对象
    private static HungerSignletonTest signleton = new HungerSignletonTest();

    private HungerSignletonTest(){};

    public static HungerSignletonTest getInstance() {
        return signleton;
    }

    public static void main(String[] args) {
        //三个线程测试单例,打印hashcode是否一致
        new Thread(()->{System.out.println(HungerSignletonTest.getInstance().hashCode()); }).start();
        new Thread(()->{System.out.println(HungerSignletonTest.getInstance().hashCode()); }).start();
        new Thread(()->{System.out.println(HungerSignletonTest.getInstance().hashCode()); }).start();
    }
}

饿汉模式是主动创建对象,如上面程序代码,JDK1.8环境中主线程启动三个线程获取HungerSignletonTest实例的hashcode是否为同一个对象,测试结果如下图所示,所有的hashcode一致证明程序只有一个实例。饿汉单例在类初始化会提前创建对象。缺点:**过早的创建对象需要提前消耗内存资源,我们需要在使用单例对象时再去创建。**下面我们看看懒汉模式代码。

2.懒汉模式 线程不安全

/**
 * @author :jiaolian
 * @date :Created in 2021-01-10 21:39
 * @description:懒汉设计模式测试
 * @modified By:
 * 公众号:叫练
 */
public class LazySignletonTest {
    private static LazySignletonTest signleton = null;
    private LazySignletonTest(){};

    public static LazySignletonTest getInstance() {
        if (signleton == null) {
            /*try {
                //创建对象睡2秒
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }*/
            signleton = new LazySignletonTest();
        }
        return signleton;
    }

    public static void main(String[] args) {
        //三个线程测试单例
        new Thread(()->{System.out.println(LazySignletonTest.getInstance().hashCode()); }).start();
        new Thread(()->{System.out.println(LazySignletonTest.getInstance().hashCode()); }).start();
        new Thread(()->{System.out.println(LazySignletonTest.getInstance().hashCode()); }).start();
    }
}

懒汉模式是需要用到单例才调用getInstance()方法创建对象,看上去没有什么问题,如果放开上面注释语句,在创建对象睡2秒,可能得到的结果如下图所示,三个线程得到的hashcode的值并不一样,说明signleton对象不是单例。在延迟的情况下,所有线程都会进入if条件语句,所以会有如下情况。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值