天天看點

Java-Singleton(單例建立-餓漢式,懶漢式)

package com.easygo.singleton;
/**
 * Java單例有兩種方式,餓漢式和懶漢式,餓漢式是在對象建立之前加載,優先于對象,而懶漢式是在對象建立完成後調用對象的方法來建立對象
 * ,了解JVM加載原理的都清楚,正真意義上的單例是餓漢式,在對象建立之前加載。
 * @author lx
 *
 */
public class Singleton {
//餓漢式
    public static Singleton singleton=null;
    static {
        singleton=new Singleton();
        
    }
    
    //懶漢式
    public static Singleton getsingleton() {
        if(null==singleton) {
            singleton=new Singleton();
            return singleton;
            
        }else {
            return singleton;
        }
        
        
    }
}
建立線程安全的單例(雙檢鎖)
      
package com.easygo.dome;

public class Th1 {
private static Th1 th1=null;
public static Th1 getTh1() {
    if(null==th1) {
        synchronized (Th1.class) {
            if(null==th1) {
                th1=new Th1();
                
            }
        }
        
    }
    return th1;
    
    
}
}      

轉載于:https://www.cnblogs.com/mature1021/p/9568607.html