/*目的:分析一下單例設計模式中,懶漢式與餓漢式在多線程中的不同!開發時我們一般選擇餓漢式,因為它簡單明了,多線程中不會出現安全問題!而餓漢式需要我們自己處理程序中存在的安全隱患,但是餓漢式的程序技術含量更高!
*/
/* class SinglePerson implements Runnable{private static SinglePerson ss = new SinglePerson("hjz", 22);//惡漢式private int age;private String name;private int count;private SinglePerson(String name, int age){this.age = age;this.name = name;}private SinglePerson(){age = 10;name = " ";}public static SinglePerson getInstance(){return ss;}public String getName(){return name;}public int getAge(){return age;}public void setIntroduceCount(){++count;}public int getIntroduceCount(){return count;}public synchronized void run(){ss.setIntroduceCount();try{Thread.sleep(20);}catch(InterruptedException e){}System.out.println("this is " + ss.getName() + " " + ss.getAge() + " 被介紹的次數是:" + ss.getIntroduceCount());}} */class SinglePerson implements Runnable{private static SinglePerson ss = null;//懶漢式private int age;private String name;private int count;private SinglePerson(String name, int age){this.age = age;this.name = name;count=0;}private SinglePerson(){age = 10;name = " ";}/*public static SinglePerson getInstance(){if(ss==null){//單例設計模式中,懶漢式在多線程中的缺憾啊!可能不能保證對象的唯一性try{Thread.sleep(10);}catch(InterruptedException e){}ss = new SinglePerson("hjz", 22);}return ss;}*//* public static synchronized SinglePerson getInstance(){//保證了對象的唯一性,也就是安全性保證了!但是每當調用該函數時if(ss==null){ //都要判斷一下同步鎖對象,降低了程序的效率!try{Thread.sleep(10);}catch(InterruptedException e){}ss = new SinglePerson("hjz", 22);}return ss;} */public static SinglePerson getInstance(){//這就是懶漢式的安全又效率的代碼!if(ss==null){//這一句是必須判斷的!synchronized(SinglePerson.class){//這一句只是其他的線程訪問時判斷if(ss==null){try{Thread.sleep(10);}catch(InterruptedException e){}ss = new SinglePerson("hjz", 22);}}}return ss;}public String getName(){return name;}public int getAge(){return age;}public void setIntroduceCount(){++count;}public int getIntroduceCount(){return count;}public synchronized void run(){ss.setIntroduceCount();System.out.println("this is " + ss.getName() + " " + ss.getAge() + " 被介紹的次數是:" + ss.getIntroduceCount());}
}class OtherThread extends Thread{public void run(){SinglePerson.getInstance().run();}
}public class Test{public static void main(String[] args){new OtherThread().start();new OtherThread().start();new OtherThread().start();new Thread(SinglePerson.getInstance()).start();}
}