深入JVM之號稱世界上所有Java程式員都會犯的一個錯誤

來源:互聯網
上載者:User
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;}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.