前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >面试题—5种单例模式写法以及单线程和多线程下的区别

面试题—5种单例模式写法以及单线程和多线程下的区别

作者头像
全栈程序员站长
发布2022-07-01 19:46:02
2550
发布2022-07-01 19:46:02
举报

大家好,又见面了,我是你们的朋友全栈君。

闲来无事看之前的博客,发现单例模式只会写2中。所以再重新开一篇博客,将目前自己所能理解的几种单例模式全部总结下。

___________________________________________________________________________________________________________

1、懒汉式(最基本的) 单线程版

写单例模式(饿汉式)的步骤:

1):必须在该类中,自己先创建出一个对象。

2):私有化自身的构造器,防止外界通过构造器创建新的对象。

3):想外暴露一个公共的静态方法用于获取自身的对象

缺点:单线程是没问题的 但是多线程就会产生线程问题 下面会介绍多线程版本

代码语言:javascript
复制
//  懒汉式类初始化的,不会创建该对象,真正需要的时候才会加载(创建),天生线程不安全,需要解决线程安全问题,所有效率比较低
public class SingletonLazy {

    private SingletonLazy() {
        System.out.println(Thread.currentThread().getName());
    }

    private static SingletonLazy singletonLazy;

    public static SingletonLazy getInstance() {
        if (singletonLazy == null) {
            singletonLazy = new SingletonLazy();
        }
        return singletonLazy;
    }

    public static void main(String[] args) {

        SingletonLazy singletonLazy1 = SingletonLazy.getInstance();
        SingletonLazy singletonLazy2 = SingletonLazy.getInstance();
        System.out.println(singletonLazy1 == singletonLazy2);   // true
    }
}

多线程版本线程不安全(最简单的案例):

代码语言:javascript
复制
public class SingletonLazy {

    private SingletonLazy() {
        System.out.println(Thread.currentThread().getName());
    }

    private static SingletonLazy singletonLazy;

    public static SingletonLazy getInstance() {
        if (singletonLazy == null) {
            singletonLazy = new SingletonLazy();
        }
        return singletonLazy;
    }

    public static void main(String[] args) {
       
        for (int i = 0; i <= 500; i++) {
            new Thread(() -> {
                try {
                    getInstance();
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }, String.valueOf(i)).start();
        }
      
       
    }
}

2、饿汉式(最基本的)

优点:线程天生安全 类在整个生命周期中只会被加载一次,因此该单例类只会创建一个实例,也就是说,线程每次都只能也必定只可以拿到这个唯一的对象 缺点:类加载的时候就会加载 static 对象 如果暂时用不到呢 就会占用极大的内存

代码语言:javascript
复制
public class SingletonHungry {
//    会浪费内存
//    byte[] data1 = new byte[1024*1024];
//    byte[] data2 = new byte[1024*1024];

    private SingletonHungry() {
        System.out.println(Thread.currentThread().getName());
    }

    //小知识: 当使用static 修饰时 会存档在 JVM的方法区  JVM垃圾回收机制 不会进行回收
    private static final SingletonHungry singletonDemo = new SingletonHungry();


    private static SingletonHungry getInstance() {
        return singletonDemo;
    }

    public static void main(String[] args) {
        
        SingletonHungry singletonDemo = getInstance();
        SingletonHungry singletonDemo2 = getInstance();

        System.out.println(singletonDemo == singletonDemo2);  // true
    }
}

3、枚举

代码语言:javascript
复制
枚举是一个特殊的类
代码语言:javascript
复制
内部将构造器进行私有化,因此不能通过New 的方式进行创建

有兴趣可以测试下 ,我这比较简单

代码语言:javascript
复制
public enum  EnumSingleton {
    INSTANCE;
    public EnumSingleton getInstance(){
        return INSTANCE;
    }
}

4、静态内部类

代码语言:javascript
复制
public class SingletonStatic {
    private SingletonStatic() {}
    public static class  SingletonClassInstance{
        private static final SingletonStatic single = new SingletonStatic();
    }
    public static SingletonStatic getInstance(){
        return SingletonClassInstance.single;
    }

    public static void main(String[] args) {
        SingletonStatic singleton1 = SingletonStatic.getInstance();
        SingletonStatic singleton2 = SingletonStatic.getInstance();

        System.out.println(singleton1 ==singleton2);
    }
}

5、DCL(双重检验锁)

在 new MultiSingletonDCL();时候由于会发生指令重排序 可能会出现问题 因此加上关键字 volatile

代码语言:javascript
复制
// 1. 分配内存空间
// 2. 执行构造方法,初始化对象
// 3. 把这个对象指向这个空间
代码语言:javascript
复制
// 双锁机制的出现是为了解决前面同步问题和性能问题

public class SingletonDCL {

    private volatile static MultiSingletonDCL multiSingletonDCL;
    private SingletonDCL() {
        System.out.println(Thread.currentThread().getName());

    }

    private static SingletonDCL getInstance() {
        if (singletonLazyDCL == null){
            synchronized (SingletonDCL.class){
                if (singletonLazyDCL == null){
                        
                    singletonLazyDCL = new SingletonDCL();
                }
            }
        }
        return singletonLazyDCL;
    }
    public static void main(String[] args) {

        SingletonDCL instance = SingletonDCL.getInstance();
        SingletonDCL instance2 = SingletonDCL.getInstance();
        System.out.println(instance == instance2);
    }
}

本文如有问题,希望大佬指正。不胜感激。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/147130.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档