栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

2021-11-01 杭州 单例模式 (借鉴-侵-删)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

2021-11-01 杭州 单例模式 (借鉴-侵-删)

这里写自定义目录标题
  • 饿汉式单例模式
  • 懒汉式单例模式

饿汉式单例模式

饿汉式单例模式在类加载的时候就立即初始化,并且创建单例对象。它绝对线程安全,在线程还没出现以前就实例化了、不可能存在访问安全问题。
优点:没有加任何锁、执行效率比较高,用户体验比懒汉式单例模式更好。
缺点:类加载的时候就初始化,不管用与不用都占着空间,可能浪费内存,“尸位素餐”。
Spring中loC容器ApplicationContext本身就是典型的饿汉式单例模式。

public class CommTest {
    private static final CommTest commtest=new CommTest();
    private CommTest(){}
    public static CommTest getInstance(){
        return commtest;
    }
}
//或者静态代码块加载
public class HungryStaticSingleton {
    private static final HungryStaticSingleton hungrySingleton;
    static {
        hungrySingleton = new HungryStaticSingleton();
    }
    private HungryStaticSingleton(){}
    public static HungryStaticSingleton getInstance(){
        return  hungrySingleton;
    }
}
懒汉式单例模式
public class CommTest {
    private static final CommTest commtest=null;
    private CommTest(){}
    public static CommTest getInstance(){
        if (commtest==null){
            return new CommTest();
        }
        return commtest;
    }

    public static void main(String[] args) {
        Runnable task=() ->{
            CommTest instance = CommTest.getInstance();
            System.out.println(Thread.currentThread().getName()+":"+instance);
        };
        Thread thread1 = new Thread(task);
        Thread thread2 = new Thread(task);

        thread1.start();
        thread2.start();

        System.out.println("END");
    }
}

结果:

END
Thread-1:net.work.util.CommTest@47b0fb92
Thread-0:net.work.util.CommTest@47b0fb92
有一定概率出现下面场景
END
Thread-0:net.work.util.CommTest@4a928248
Thread-1:net.work.util.CommTest@24561a0a

出现了两个不一样的结果,说明这个单例存在线程安全隐患
解决方式一:在getInstance加synchronized同步锁

public static synchronized CommTest getInstance(){
        if (commtest==null){
            commtest = new CommTest();
        }
        return commtest;
    }
结果:只会相同
END
Thread-1:net.work.util.CommTest@5c3e70d7
Thread-0:net.work.util.CommTest@5c3e70d7

解决方式二:双层检验锁

public class CommTest {
    private volatile static CommTest commtest=null;
    private CommTest(){}
    public static CommTest getInstance(){
        if (commtest==null){
            synchronized (CommTest.class) {
                commtest = new CommTest();
            }
        }
        return commtest;
    }

    public static void main(String[] args) {
        Runnable task=() ->{
            CommTest instance = CommTest.getInstance();
            System.out.println(Thread.currentThread().getName()+":"+instance);
        };
        Thread thread1 = new Thread(task);
        Thread thread2 = new Thread(task);

        thread1.start();
        thread2.start();

        System.out.println("END");
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/389559.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号