多线程(八)---单例模式并发访问

多线程(八)---单例模式并发访问

多线程并发访问会出现安全问题,加了同步就能够解决问题,不管是同步函数仍是同步代码块均可以。

如何解决懒汉模式效率低问题?

能够经过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();
    }
}
相关文章
相关标签/搜索