單例設計模式之懶漢式(線程安全)


package com.waibizi.demo04;


/**
 * 懶漢式線程安全寫法
 * 優點:解決了線程不安全的問題
 * 缺點:效率太低了,每個線程在想獲得類的實例的時候,執行getInstance()方法都要進行同步,而其實這個方法只執行一次實例化代碼就可以了,后面的想獲得該類實例的時候
 *            直接return即可了
 * 結論:在實際的開發中不推薦這種寫法
 * @author 歪鼻子
 *
 */
public class Singleton_pattern {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Singleton test = Singleton.getInstance();
        Singleton test1 = Singleton.getInstance();
        System.out.println(test.hashCode());
        System.out.println(test1.hashCode());

    }

}
@SuppressWarnings("all")
class Singleton{
    private static Singleton instance;
    private Singleton() {
        
    }
    
    //提供一個靜態的公有方法,當使用該方法時,才去創建instance
    //即懶漢式加載(線程安全)
    public static synchronized Singleton getInstance() {
        if(instance==null) {
            System.out.println("我只初始化了這一次哦");
            instance=new Singleton();

        //線程安全不能用的方式
        // synchronized(Singleton.class) {
        // instance=new Singleton();
        // }


        }
        return instance;
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM