Java面试题之JVM相关(1)

开心一笑

女朋友给她男友打电话,电话接通的那一刻,
手机里竟然传出一句:对不起,您所拨打的电话正在通话中,请稍后再拨……
女朋友一听就知道是她男友的声音,
所以没有挂断问:不是还有一句英文吗?
对面支支吾吾:Sorry,you……the number ……

提出问题

一道很坑的面试题,但是对理解JVM很有帮助???

解决问题

例一:

package com.evada.de;

class Singleton{

    private static Singleton singleton = new Singleton();
    public static int counter1;
    public static long counter2 = 0;

    private Singleton(){
        counter1 ++;
        counter2 ++;
    }

    public static Singleton getInstance(){
        return singleton;
    }
}

/**
 * Created by Ay on 2016/5/24.
 */
public class LambdaTest {

    public static void main(String[] args) throws Exception{
        Singleton singleton = Singleton.getInstance();
        System.out.println("counter1 :" + Singleton.counter1);
        System.out.println("counter2 :" + Singleton.counter2);
    }
}

运行结果:

counter1 :1
counter2 :0

解释:

从main函数开始,根据JVM对类的加载机制,Singleton.getInstance()主动使用,会触发类的加载,首先会为类的静态变量赋予初始值(程序从上到下执行),
即:Singleton singleton = null,counter1 = 0,counter2 = 0.

然后会进行类的初始化,即singleton = new Singleton(),会触发构造函数,执行:
    counter1 ++;
    counter2 ++;
后
    counter1 = 1,
    counter2 = 1

最后,类在初始化后,为类的静态变量赋予正确的初始值,为用户赋予的正确值(从上到下)
即:
    
    public static int counter1;//无用户赋值
    public static long counter2 = 0;//用户赋予初始值0
最终结果:
    counter1 :1
    counter2 :0

例二:

package com.evada.de;

class Singleton{

    public static int counter1;
    public static long counter2 = 0;
    private static Singleton singleton = new Singleton();

    private Singleton(){
        counter1 ++;
        counter2 ++;
    }

    public static Singleton getInstance(){
        return singleton;
    }
}

/**
 * Created by Ay on 2016/5/24.
 */
public class LambdaTest {

    public static void main(String[] args) throws Exception{
        Singleton singleton = Singleton.getInstance();
        System.out.println("counter1 :" + Singleton.counter1);
        System.out.println("counter2 :" + Singleton.counter2);
    }
}

运行结果

counter1 :1
counter2 :1

解释:

从main函数开始,根据JVM对类的加载机制,Singleton.getInstance()主动使用,会触发类的加载,首先会为类的静态变量赋予初始值(程序从上到下执行),
即:Singleton singleton = null,counter1 = 0,counter2 = 0.

然后会进行类的初始化,即
    public static int counter1;//无用户赋值
    public static long counter2 = 0;//用户赋予初始值0
后
    counter1 = 0,
    counter2 = 0    

singleton = new

Singleton(),会触发构造函数,执行:
counter1 ++;
counter2 ++;

最终结果:
    counter1 :1
    counter2 :1

读书感悟

来自《红猪》

  • 不会飞的猪,就只是平凡的猪
  • 爱上他,不如先习惯他!

你可能感兴趣的:(Java面试题之JVM相关(1))