深入JVM之号称世界上所有Java程序员都会犯的一个错误

来源:互联网 发布:诚实国度的爱丽丝 知乎 编辑:程序博客网 时间:2024/04/28 01:06
package com.jadyer.classloader;/** * 深入JVM之号称世界上所有Java程序员都会犯的一个错误 * @author 宏宇 * @editor Jan 24, 2012 7:49:18 PM * @see 这是一个很无耻的面试题,多么卑鄙的人才能写出这种自己给自己找麻烦的代码啊~~ */public class ClassLoadTest {public static void main(String[] args) {SingletonFront singletonFront = SingletonFront.getInstance();System.out.println("counter11 = " + singletonFront.counter11);System.out.println("counter22 = " + singletonFront.counter22);System.out.println("=============");SingletonBack singletonBack = SingletonBack.getInstance();System.out.println("counter33 = " + singletonBack.counter33);System.out.println("counter44 = " + singletonBack.counter44);}}/** * 单例类:在变量之前new的实例 * @see Step01:为静态变量分配内存并初始化为默认值 * @see    singletonFront=null,counter11=0,counter22=0 * @see Step02:为静态变量赋正确的初始值,并初始化类的实例 * @see   singletonFront=new SingletonFront(),counter11=1,counter22先因为构造方法等于壹之后又因为初始值等于零 */class SingletonFront{private static SingletonFront singletonFront = new SingletonFront(); //注意这个位置public static int counter11;public static int counter22 = 0;private SingletonFront(){counter11++;counter22++;}public static SingletonFront getInstance(){return singletonFront;}}/** * 单例类:在变量之后new的实例 * @see Step01:为静态变量分配内存并初始化为默认值 * @see    counter11=0,counter22=0,singletonFront=null * @see Step02:为静态变量赋正确的初始值,并初始化类的实例 * @see   counter11与counter22都是先等于零之后又因为构造方法才等于壹,singletonFront=new SingletonFront() */class SingletonBack{public static int counter33;public static int counter44 = 0;private static SingletonBack singletonBack = new SingletonBack(); //注意这个位置private SingletonBack(){counter33++;counter44++;}public static SingletonBack getInstance(){return singletonBack;}}
原创粉丝点击