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

本文探讨了多线程环境下单例模式的实现方法,包括懒汉模式和恶汉模式,并详细介绍了如何通过同步机制解决并发访问时的安全问题。

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

多线程并发访问会出现安全问题,加了同步就可以解决问题,无论是同步函数还是同步代码块都可以。

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

可以通过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();
    }
}

转载于:https://my.oschina.net/u/3136594/blog/865889

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值