面试题—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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • tomcat宕机解决方法

    tomcat宕机解决方法最近项目出现tomcat宕机的情况,即项目运行一段时间后tomcat就会停止运行,解决方法步骤如下:首先进入linux服务器,使用命令top进行查看,发现tomcat的cpu利用率很高,超过100%接着,使用命令ps-ef|greptomcat,查找到对应的pid接着使用jmap-heappid.发现PermGen的利用率达到了99.99%,所以初步确定了问题是出在永久带内存

    2022年7月26日
    12
  • windows下安装docker_bindService

    windows下安装docker_bindService1、下载BINDhttp://ftp.isc.org/isc/bind9/9.4.3/BIND9.4.3.zip2、安装下载回来是zip的压缩包,解压以后直接双击BINDInstall.exe安装,默认安装路径是C:\WINDOWS\system32\dns。bind在win32下将自己注册成服务,服务名叫ISCBIND,程序名为named.exe,启动服务需要用一专有帐户,默认名称为named,密码由安装者自定义。点击install以后,程序便安装在C:\WINDOWS\system32\dns

    2022年10月30日
    0
  • linux查看网卡信息的几种方法(命令)「建议收藏」

    linux查看网卡信息的几种方法(命令)「建议收藏」这两天由于测试需求需需要查看服务器上有几个网卡以及每个网卡信息等,因此收集一些查看这些信息的方法。一、首先是最简单明了的两个命令,ifconfig和lspci。1.ifconfig:最常用的配置和查看网络接口信息的命令,服务器上执行此命令会得到类下文的内容,一下内容可看到多个设备和设备状态、信息。[oracle@mori~]$[oracle@mor

    2022年5月8日
    64
  • Windows安装git客户端[通俗易懂]

    Windows安装git客户端[通俗易懂]1、客户端安装工具如下Git-2.12.2.2-64-bit.exe下载地址:https://gitforwindows.org/,界面如下TortoiseGit-2.4.0.2-64bit.msi下载地址:https://tortoisegit.org/,界面如下Git-2.12.2.2-64-bit.exe:是需要安装的git真正工具TortoiseGit-2.4.0.2-64bit.msi:…

    2022年9月7日
    0
  • Objective—C_java中一个类有几个父类

    Objective—C_java中一个类有几个父类Class的定义1:调用系统的类eg:classpointertoobejctobjectNSString*message=@"Hello";NSAutoreleas

    2022年8月5日
    3
  • 彻底卸载JDK环境教程

    彻底卸载JDK环境教程JDK完全卸载教程卸载JDK删除残留文件清空环境变量清空注册表卸载JDK删除残留文件清空环境变量清空注册表

    2022年6月25日
    46

发表回复

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

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