线程安全又不堵塞的单例模式

单例模式,我们平常写的有好几种,下面有其中的五种

/**

 * 单例模式1,存在线程不安全问题,若不考虑线程安全可以用
 *
 * @author tarena
 *
 */
class Singleton1 {
    private static Singleton1 singleton;

    private Singleton1() {
    }

    public static Singleton1 getInstance() {
        if (singleton == null) {
            singleton = new Singleton1();
        }
        return singleton;
    }

}


--------------------------------------------------------------------------------------------------------------------------------------



/**
 * 单例模式2,线程安全了,但会因为线程同步,引起线程堵塞
 * 若是不考虑大并发情况下,也可以用。
 * @author tarena
 *
 */
class Singleton2 {
    private static Singleton2 singleton;

    private Singleton2() {
    }

    public synchronized static Singleton2 getInstance() {
        if (singleton == null) {
            singleton = new Singleton2();
        }
        return singleton;
    }
}


--------------------------------------------------------------------------------------------------------------------------------------



/**

 * 单例模式3,线程安全了,线程同步访问速度也优化了些,但在一开始时的并发还是会出现堵塞
 *
 * @author tarena
 *
 */
class Singleton3 {
    private static Singleton3 singleton;

    private Singleton3() {
    }

    public static Singleton3 getInstance() {
        if (singleton == null) {
            synchronized (Singleton3.class) {
                if (singleton == null) {
                    singleton = new Singleton3();
                }
            }
        }
        return singleton;
    }
}


--------------------------------------------------------------------------------------------------------------------------------------



/**
 * 单例模式4,线程安全了,并发访问速度更快了,
 *  缺点:假如对象比较大,类加载时就创建了此对象,假如不使用,就可能长时间占用内存。
 * @author tarena
 *
 */
class Singleton4 {//非大对象时用
    private static final Singleton4 singleton=new Singleton4();
    private Singleton4(){
        
    }
    public static Singleton4 getInstance() {
        return singleton;
    }

}


--------------------------------------------------------------------------------------------------------------------------------------



/**
 * 单例模式5,线程安全了,并发访问速度更快了
 *
 * @author tarena
 *
 */
class Singleton5 {//大对象时,就用这种
    private Singleton5(){
    }
    
    //什么时候需要什么时候构建实例。
    static class Lazy{
        private static final Singleton5 singleton=new Singleton5();
    }
    public static Singleton5 getInstance() {
        return Lazy.singleton;

    }

}


以上五种供参考学习,推荐用第五种。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值