zoukankan      html  css  js  c++  java
  • 单例模式之静态内部类实现

    1.代码示例

    public class Singleton
    {
    	private Singleton(){}
    	
    	static {
    		System.out.println("This's static code block!");
    	}
    	
    	private static class SingletonHandler {
    		private static Singleton singleton = new Singleton();
            static {
                System.out.println("This's innerClass's static code block");
            }
    	}
    	
    	public static Singleton getInstance(){
    		return SingletonHandler.singleton;
    	}
    	
    	public static void display(){
    		System.out.println("This's display!");
    	}
    }
    
    
    public class SingletonTest
    {
    	private SingletonTest(){}
    	
    	static class MyThread extends Thread {
    		@Override
    		public void run()
    		{
    			super.run();
    			System.out.println("Thread running_"+Singleton.getInstance());
    		}
    	}
    	
    	public static void main(String[] args)
    	{
    		MyThread th1 = new MyThread();
    		MyThread th2 = new MyThread();
    		MyThread th3 = new MyThread();
    		/*@1
    		th1.start();
    		th2.start();
    		th3.start();
    		*/
    		
    		/*@2
    		Singleton.display();
    		*/
    	}
    }
    

    2. 运行结果及解释

    情况一(注释 @1代码,注释 @2的代码)
    //运行结果 为空
    

    解释:外部类和内部类都没有加载

    情况二(执行 @1代码)
    //运行结果
    This's static code block!
    This's innerClass's static code block
    Thread running_com.singleton.Singleton@4f19c297
    Thread running_com.singleton.Singleton@4f19c297
    Thread running_com.singleton.Singleton@4f19c297
    

    解释: 外部类Singleton和内部类SingletonHandler都加载了,因为他们的静态代码块加载了

    情况三(注释 @1代码,执行 @2的代码)
    //运行结果
    This's static code block!
    This's display!
    

    解释:外部类加载了,而内部类没有加载,因为加载了类,就一定会执行静态代码块

    3. 结论

    终上实验:内部类SingletonHandler只有在getInstance()方法第一次调用的时候才会被加载(实现了延迟加载效果),而且其加载过程是线程安全的(实现线程安全)。内部类加载的时候只实例化了一次instance

  • 相关阅读:
    【css】用纯 CSS 判断鼠标进入的方向
    【window】系统禁止运行脚本
    【go】VSCode配置Go插件和debug设置
    【PHP】php之Trait详解
    【layui】laydata 自定义日期之外格式的处理办法
    【PHP】防止视频资源被下载的解决办法
    【Markdown】 编辑器Editor.md集成使用
    代码之间为什么要加空格?
    求求你,别问了,Java字符串是不可变的
    养生吧,程序员!
  • 原文地址:https://www.cnblogs.com/Trainoo/p/8044606.html
Copyright © 2011-2022 走看看