程序笔记   发布时间:2022-07-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了利用static来实现单例模式大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

一:之前旧的写法

class Singleton{
    private Singleton() {}
    private static Singleton instance = null;
    public synchronized static Singleton getInstance() {
            if (instance == null) {
                instance = new Singleton();
            }
            return instance;
        }
}

就利用Sington.getInstace就可以了,获得的是同一个实例。上面那个代码有两个优点:

  1. 懒加载,把在堆创建实例这个行为延迟到类的使用时。
  2. 锁效果,防止生成多个实例,因为synchronized修饰这个static方法,所以相当于给这个方法加上了一个类锁🔒。

 

二:static代码块的效果

先来看一段代码:

class StaticClass{
    private static int a = 1;
    static{
        System.out.println("语句1");
        System.out.println("语句2");
    }
    static{
        System.out.println("语句3");
        System.out.println("语句4");
    }
}

当在多个线程同时触发类的初始化过程的时候(在初始化过程,类的static变量会被赋值为JVM默认值并且static代码块会被执行),为什么static不会被多次执行?因为有可能两个线程同时检测到类还没被初始化,然后都执行static代码块,结果就把语句1234多打印了,为什么上述情况不会发生。

Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Class.forName("StaticClass");//这一行触发类的初始化导致静态代码块执行
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });
        thread1.start();
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Class.forName("StaticClass");//同样
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });
        thread2.start();

结果如下:

语句1
语句2
语句3
语句4

有一段英文对其进行了解释:

static initialization block can be triggered from multiple parallel threads (when the loading of the class happens in the first time), Java runtime guarantees that it will be executed only once and in thread-safe manner + when we have more than 1 static block - it guarantees the sequential execution of the blocks, 也就是说,java runtime帮我们做了两件事:

  1. 并行线程中,都出现了第一次初始化类的情况,保证类的初始化只执行一次。
  2. 保证static代码块的顺序执行

 

三:单例的另一种写法

有了对static的知识的了解之后,我们可以写出这样的单例模式:

class Singleton{
    private Singleton() {}
    private static class NestedClass{
       static Singleton instance = new Singleton();//这条赋值语句会在初始化时才运行
    }
    public static Singleton getInstance() {
        return NestedClass.instance;
    }
}
  1. 懒加载,因为static语句会在初始化时才赋值运行,达到了懒加载的效果。
  2. 锁🔒的效果由Java runtime保证,虚拟机帮我们保证static语句在初始化时只会执行一次。

 

四:总结

如果不知道static的基础知识和虚拟机类加载的知识,我可能并不会知道这一种方法。理论永远先行于技术,要学好理论才能从根本上提升自己。

 

本博文站在以下这位巨人的肩膀上:https://www.linkedin.com/pulse/static-variables-methods-java-where-jvm-stores-them-kotlin-malisciuc

 

大佬总结

以上是大佬教程为你收集整理的利用static来实现单例模式全部内容,希望文章能够帮你解决利用static来实现单例模式所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: