多线程下的单例模式

        单例模式就不在这里详细介绍了,这里要了解的是如何使单例模式遇到多线程是安全的。

   单例模式分为饿汉模式和懒汉模式。

   饿汉模式就类在加载的时候就创建实例,当使用类的时候已经将对象创建好了 

public class SingletonMode1 {

    private static SingletonMode1 singletonMode1 = new SingletonMode1();
    private SingletonMode1(){}
    public static SingletonMode1 getInstance(){
        return singletonMode1;
    }

    public static void main(String[] args){

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("Get hashCode: " + SingletonMode1.getInstance().hashCode());
            }
        };

        Thread thread1 = new Thread(runnable);
        Thread thread2 = new Thread(runnable);
        Thread thread3 = new Thread(runnable);
        Thread thread4 = new Thread(runnable);
        Thread thread5 = new Thread(runnable);
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        thread5.start();
    }
}

运行结果,获取的是同一个对象


懒汉模式是指在使用的时候才去创建对象实例,网上介绍多线程模式下怎样创建线程安全的单例模式很多,这里再回顾下,一步步去构架、完善,分析并解决问题。

最简单的单例模式

public class SingletonMode2 {

    private SingletonMode2 mode2 = null;
    private SingletonMode2(){}
    public static SingletonMode2 getInstance(){

        if(mode2 == null){
            mode2 = new SingletonMode2();
        }
        return mode2;
    }
}

该写法在单线程情况下没有问题的,那么在多线程模式下回怎样呢?

public class SingletonMode2 {

    private static SingletonMode2 mode2 = null;
    private SingletonMode2(){}
    public static SingletonMode2 getInstance(){
        try{
            if(mode2 == null){
                Thread.s
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值