现在的位置: 首页 > 综合 > 正文

有趣的jvm加载的过程说明

2018年02月04日 ⁄ 综合 ⁄ 共 718字 ⁄ 字号 评论关闭

代码

public class MyTest {
public static void main(String[] args) {// step 6
Singleton singleton = Singleton.getInstance();//step 7
System.out.println("counter1= " + singleton.counter1);
System.out.println("counter2= " + singleton.counter2);
}

}

class Singleton {
private static Singleton singleton = new Singleton();// step 1
public static int counter1; // step 2
public static int counter2 = 0;// step 3

private Singleton() {// step 4
counter1++;
counter2++;
}

public static Singleton getInstance() {// step 5
return singleton;
}

}

结果

counter1= 1
counter2= 0    奇怪的结果

执行顺序

a. 调用主入口的方法,首先加载MyTest类

b. 调用main方法

7. 

a. 调用静态方法时,先初始化静态变量的默认值,再赋值

b. singleton 为null   counter1为0   counter2 为0 赋默认值

c. 再赋值  = Singleton.getInstance();    导致调用4 counter1为1  counter2 为1

d. 在赋值  counter1  没有赋值所以还是1     counter1  有赋值所以是0了

让结果变的正常

将1放到3的后面

抱歉!评论已关闭.