(單例設計模式中)懶漢式與餓漢式在多執行緒中的不同

2021-09-20 13:53:19 字數 3301 閱讀 6625

9

120

121

122

123

124

125

126

127

128

129

130

131

/*

目的:分析一下單例設計模式中,懶漢式與餓漢式在多執行緒中的不同!

開發時我們一般選擇餓漢式,因為它簡單明瞭,多執行緒中不會出現安全問題!

而餓漢式需要我們自己處理程式中存在的安全隱患,但是餓漢式的程式技術含量更高!

*/

/* class singleperson implements runnable

private singleperson()

public static singleperson getinstance()

public string getname()

public int getage()

public void setintroducecount()

public int getintroducecount()

public synchronized void run()catch(interruptedexception e)

system.out.println("this is " + ss.getname() + " " + ss.getage() + " 被介紹的次數是:" + ss.getintroducecount());

}

}  */

classsinglepersonimplementsrunnable

privatesingleperson()

/*public static singleperson getinstance()catch(interruptedexception e){}

ss = new singleperson("hjz", 22);

}

return ss;

}*/

/* public static synchronized singleperson getinstance()catch(interruptedexception e){}

ss = new singleperson("hjz", 22);

}

return ss;

} */

publicstaticsingleperson getinstance()catch(interruptedexception e){}

ss =newsingleperson("hjz",22);

}

}

}

returnss;

}

publicstring getname()

publicintgetage()

publicvoidsetintroducecount()

publicintgetintroducecount()

publicsynchronizedvoidrun()

}

classotherthreadextendsthread

}

publicclasstest

}

單例設計模式 懶漢式與餓漢式

1 概念 在某些場合中,乙個類對外提供乙個且只提供乙個物件時,這樣的類的類叫做單例類。編寫單例類的模式叫做單例設計模式,是程式設計的總結。2 思路 在程式中,如果其它的類需要用到這個類的物件,都是通過new的方式建立類物件,這時就根本無法控制其他類new物件的個數,那麼如何保證保證只有乙個new物件...

設計模式 單例模式 餓漢式,懶漢式

餓漢式 將物件的實現提前準備好,物件指向的記憶體只能有乙個。public class singlection1 餓漢式單例實現 將物件的實現提前準備好 private static final singlection1 single1 new singlection1 靜態工廠 public sta...

單例模式 懶漢式與餓漢式

什麼是單例設計模式 保證這個類的物件永遠有且只有乙個。單例設計模式有兩種 見如下兩種宣告方式 1.懶漢式 設計單例模式 懶漢式 先建立乙個私有的靜態物件 private static user user 建立乙個私有的構造方法 private user 建立乙個公有的靜態的返回物件的方法,需要判斷 ...