大佬教程收集整理的这篇文章主要介绍了利用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就可以了,获得的是同一个实例。上面那个代码有两个优点:
先来看一段代码:
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帮我们做了两件事:
有了对static的知识的了解之后,我们可以写出这样的单例模式:
class Singleton{ private Singleton() {} private static class NestedClass{ static Singleton instance = new Singleton();//这条赋值语句会在初始化时才运行 } public static Singleton getInstance() { return NestedClass.instance; } }
如果不知道static的基础知识和虚拟机类加载的知识,我可能并不会知道这一种方法。理论永远先行于技术,要学好理论才能从根本上提升自己。
本博文站在以下这位巨人的肩膀上:https://www.linkedin.com/pulse/static-variables-methods-java-where-jvm-stores-them-kotlin-malisciuc
以上是大佬教程为你收集整理的利用static来实现单例模式全部内容,希望文章能够帮你解决利用static来实现单例模式所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。