发表文章

[最新] 单例模式在多线程下的线程安全问题

cheriyu 5月前 2


方法一

/**
 * 性能差---原因:每次调用方法之前先加锁
 **/
public class GetInstanceSingleton {
    private GetInstanceSingleton(){}
    private static GetInstanceSingleton getInstanceSingleton;
    public static synchronized GetInstanceSingleton getInstance(){
        if (getInstanceSingleton==null){
            getInstanceSingleton=new GetInstanceSingleton();
        }
        return getInstanceSingleton;
    }
}

方法二

/**
 * 不管用到用不到,先在类加载时初始化,浪费内存
 * **/
public class FirstNewSingleton {
    private static FirstNewSingleton firstNewSingleton=new FirstNewSingleton();
    private FirstNewSingleton(){}
    public static FirstNewSingleton getInstance(){
        return firstNewSingleton;
    }
}
方法三
/**
 * 双重枷锁
 * java5以上版本才适用
 * **/
class DoubleLockSingleton{
    private volatile static DoubleLockSingleton doubleLockSingleton;
    private DoubleLockSingleton(){}
    public static DoubleLockSingleton getInstance(){
        if(doubleLockSingleton==null){
            synchronized (DoubleLockSingleton.class){
                if (doubleLockSingleton==null){
                    doubleLockSingleton=new DoubleLockSingleton();
                }
            }
        }
    return doubleLockSingleton;
    }
        }


相关推荐
最新评论 (0)
返回
发表文章
cheriyu
文章数
54
评论数
0
注册排名
1008123