本文講解兩方面的內容
1.枚舉的使用
2.多線程中單例模式的實現
1.枚舉的使用
參看http://developer.51cto.com/art/201107/275031.htm
http://www.cnblogs.com/zhaoyanjun/p/5659811.html
自定義枚舉類如下
public class MyObject { public enum Color { RED("紅色", 1), GREEN("綠色", 2), BLANK("白色", 3), YELLO("黃色", 4);//枚舉變量 //枚舉變量的屬性,和枚舉變量對應 PRivate String name ; private int index ; //枚舉類的構造方法,私有是為了防止被實例化 private Color( String name , int index ){ this.name = name ; this.index = index ; } //set,get方法 public String getName() { return name; } public void setName(String name) { this.name = name; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } }}2.多線程中單例模式的實現
(1)使用靜態變量加載(餓漢式)
(2)延遲加載(懶漢式)
懶漢式中的同步問題解決:
public class MyObject { private volatile static MyObject myObject; public static MyObject getInstance(){ try{ if(myObject!=null){ // }else{ Thread.sleep(3000);//模擬創建對象的準備性工作 synchronized (MyObject.class){ //再次判斷是為了保證可能有多個線程停在上面一步,為了確保只new一個實例; //可能當該線程第一次if時為null,在sleep過程中,剛好已經有線程new實例了,需要再次判斷 if(myObject==null){ myObject=new MyObject(); } } } } catch (InterruptedException e) { e.printStackTrace(); } return myObject; }}(3)使用靜態內置類實現單例模式這個和靜態變量加載相似,只是將該語句添加到內部類中
(4)使用靜態代碼塊實現單例模式
(5)序列化與反序列化中出先new實例,破壞了單例;解決方法是在反序列化中使用readResolve()方法獲取對象
(6) 使用enum枚舉實現單例模式
public enum MyObject2 { connectionFactory;//枚舉變量 private Connection connection;//枚舉變量的屬性 private MyObject2(){ //在此處完成屬性的賦值 //connection=..... } //返回該屬性 public Connection getConnection(){ return connection; }}如上所示,即便是多個線程獲取連接,也只會有一個connection
|
新聞熱點
疑難解答