zoukankan      html  css  js  c++  java
  • JVM 初始化阶段的重要意义分析

     1、创建一个Mytest6类和Singleton类

    public class MyTest6 {
    
        public static void main(String[] args) {
            Singleton singleton = Singleton.getInstance();
            System.out.println("counter1:" +Singleton.counter1);
            System.out.println("counter2:" +Singleton.counter2);
        }
    }
    
    class  Singleton{
        public static  int counter1 ;
    
        public static int counter2 = 0;
    
        private static  Singleton singleton = new Singleton();
    
        private Singleton(){
            counter1 ++;
            counter2 ++;
        }
    
        public static  Singleton getInstance(){
            return  singleton;
        }
    
    
    }
    

      输出结果

    counter1:1
    counter2:1
    

      

    2、将counter2成员变量的位置移动到构造函数后面

    public class MyTest6 {
    
        public static void main(String[] args) {
            Singleton singleton = Singleton.getInstance();
            System.out.println("counter1:" +Singleton.counter1);
            System.out.println("counter2:" +Singleton.counter2);
        }
    }
    
    class  Singleton{
        public static  int counter1 ;
    
        private static  Singleton singleton = new Singleton();
    
        private Singleton(){
            counter1 ++;
            counter2 ++;
            System.out.println("Singleton counter1:" +counter1);
            System.out.println("Singleton counter2:" +counter2);
        }
    
        public static int counter2 = 0;
    
        public static  Singleton getInstance(){
            return  singleton;
        }
    
    
    }
    

      输出结果如下:

    Singleton counter1:1
    Singleton counter2:1
    counter1:1
    counter2:0
    

      首先Singleton singleton = Singleton.getInstance(); 是调用Singleton类的getInstance(),属于主动调用。Singleton在准备阶段,按照声明的顺序,赋予所有成员变量默认值。在初始化阶段,构造函数里couonter1和counter2的值变为1,但是后面counter2的值又被赋值为0。 所以打印了上面的结果。

    上面代码中的构造函数里counter2 ++;

    准备阶段的意义:如果没有准备阶段,counter2是没有值的,更不会有++操作
  • 相关阅读:
    UML学习
    A problem has been encountered while loading the setup components. VS2008
    C#获取资源中的图片文件
    [网络技巧]一个网线头来测试网络程序
    通过传递"窗体的名字"来实例化窗体
    [解决方案] Flex TypeError: Error #1007: 尝试实例化的函数不是构造函数。
    Flex编译器的一些参数
    ArcGIS 9.3安装流程(包括Desktop和Server)
    Oracle Wrong solution [整理中]
    What's DOM?(1)
  • 原文地址:https://www.cnblogs.com/linlf03/p/10990435.html
Copyright © 2011-2022 走看看