多線程(八)---單例模式併發訪問

多線程(八)---單例模式併發訪問

多線程併發訪問會出現安全問題,加了同步就能夠解決問題,不管是同步函數仍是同步代碼塊均可以。

如何解決懶漢模式效率低問題?

能夠經過if對單例對象的雙重判斷形式

// 惡漢模式
class Singleton{

    private Singleton(){}
    private static final Singleton SINGLETON_INSTANCE = new Singleton();
    public Singleton getInstance(){
        return SINGLETON_INSTANCE;
    }
}

/**
 * 懶漢模式
 */
class SingletonLazy{
    private SingletonLazy(){}
    private SingletonLazy s = null;

    public SingletonLazy getLazyInstance(){
        if(s == null){
            s = new SingletonLazy();
        }
        return s;
    }
}

/**
 * 多線程訪問,懶漢模式, 解決效率,安全問題
 */
class SingletonLazyThread{
    private SingletonLazyThread(){}
    private SingletonLazyThread s = null;

    public SingletonLazyThread getLazyInstance(){
        if(s == null){
            synchronized (SingletonLazyThread.class) {
                if(s == null){
                    s = new SingletonLazyThread();
                }
            }
        }
        return s;
    }
}
public class SingletonThread {
    public static void main(String[] args) {
        System.out.println();
    }
}
相關文章
相關標籤/搜索