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

面试题—5种单例模式写法以及单线程和多线程下的区别闲来无事看之前的博客,发现单例模式只会写2中。所以再重新开一篇博客,将目前自己所能理解的几种单例模式全部总结下。______________________________________________________________________________________________________________________1、懒汉式(最基本的) 单线程版写单例模式(饿汉式)的步骤: 1):必须在该类中,自己先创建出一个对象。 2):私有化自身的…

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

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

___________________________________________________________________________________________________________

 

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

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

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

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

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

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

//  懒汉式类初始化的,不会创建该对象,真正需要的时候才会加载(创建),天生线程不安全,需要解决线程安全问题,所有效率比较低
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
    }
}

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

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 对象 如果暂时用不到呢  就会占用极大的内存
 



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、枚举

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

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

public enum  EnumSingleton {
    INSTANCE;
    public EnumSingleton getInstance(){
        return INSTANCE;
    }
}

4、静态内部类

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

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

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.net/147130.html原文链接:https://javaforall.net

赞 (0)
全栈程序员-站长的头像全栈程序员-站长

相关推荐

  • goland2021.8激活码(注册激活)[通俗易懂]

    (goland2021.8激活码)本文适用于JetBrains家族所有ide,包括IntelliJidea,phpstorm,webstorm,pycharm,datagrip等。IntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,下面是详细链接哦~https://javaforall.net/100143.html…

    2022年3月25日
  • 7、注解@Mapper、@MapperScan

    7、注解@Mapper、@MapperScan1、@Mapper注解:作用:在接口类上添加了@Mapper,在编译之后会生成相应的接口实现类添加位置:接口类上面@MapperpublicinterfaceUserDAO{//代码}如果想要每个接口都要变成实现类,那么需要在每个接口类上加上@Mapper注解,比较麻烦,解决这个问题用@MapperScan2、@MapperScan作用:指定要变成实现类的接口所在的…

    2022年5月1日
  • 微信小程序真机预览图片图标无法显示怎么办_小程序进去不显示内容

    微信小程序真机预览图片图标无法显示怎么办_小程序进去不显示内容注意点:1.路径问题,路径最好不要超过两个:比如/images 这是一个,../images这是两个2.图片用的是<img/>不是<image/>3.图片名、文件夹名不能为中文,不能有空格4.图片的http地址为小写、图片后缀名为小写…

    2022年8月18日
  • crontab使用方法_crontab 表达式

    crontab使用方法_crontab 表达式crontab用法与实例本文基于ubuntu18.04在Linux系统的实际使用中,可能会经常碰到让系统在某个特定时间执行某些任务的情况,比如定时采集服务器的状态信息、负载状况;定时执行某些任务/脚本来对远端进行数据采集等。这里将介绍下crontab的配置参数以及一些使用实例。crontab配置文件Linux下的任务调度分为两类:系统任务调度和用户任务调度。Linux系统任务是由cron(crond)这个系统服务来控制的,这个系统服务是默认启动的。用户自己设置的计划任务则使用cron

    2022年8月24日
  • c语言最大公约数怎么求算法_最小公倍数c语言算法

    c语言最大公约数怎么求算法_最小公倍数c语言算法1、相减法2、穷举法3、辗转相除法

    2022年10月31日
  • windows loader v2.2_Windows Modules Installer

    windows loader v2.2_Windows Modules Installer这是WindowsLoader最新版本,解决了Win7+Win8双系统情况下,Win7“软改”激活的失效异常。目前网上“软改”工具尽管不少但制作精良者不多。特别是制作技术精湛、支持版本众多的更是凤毛麟角。我对激活工具历来要求比较苛刻。今天向大家推荐的这款“软改”工具,支持包括Win7在内的MicrosoftWindows多版本永久激活。值得各位网友收藏使用。可对以下32位/64位…

    2022年10月12日

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号