併發系列—volatile實現DCL單例模式

DCL單例模式:double check lock 單例模式

public class DCLCompnent {
    private static volatile DCLCompnent instance;

    public static final DCLCompnent getInstance(){
        if(null==instance){
            synchronized (DCLCompnent.class){
                if(null==instance){
                    try {
                        Thread.sleep(10);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    instance = new DCLCompnent();
                }
            }
        }
        return instance;
    }

    private DCLCompnent(){};
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章