有趣的jvm加载的过程说明

代码

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的后面









  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值