多线程环境下单例模式(java23中设计模式)

多线程环境下单例模式(java23中设计模式)
一,在类加载时创建实例化单例对象(线程安全,并且不需要同步);

package test;

/**
 * @author Administrator
 * 多线程变成单例模式——1
 */
public class SingletonTest {

    //类加载是创建一个对象
    private static SingletonTest singleton = new SingletonTest(); 

    //私有构造方法,防止被实例化
    private SingletonTest(){

    }

    //获取单例对象
    public SingletonTest getInstance(){
        return singleton;
    }

}

二,双重判断模式(有缺陷,不建议使用)

package test;

/**
 * @author Administrator 
 * 多线程变成单例模式——2
 */
public class SingletonTest {

    // 类加载是创建一个对象
    private static SingletonTest singleton = null;

    // 私有构造方法,防止被实例化
    private SingletonTest() {

    }

    // 获取单例对象
    public static SingletonTest getInstance() {
        if (singleton == null) {
            synchronized (SingletonTest.class) { //同步
                if (singleton == null) {
                    singleton = new SingletonTest();
                }
            }
        }

        return singleton;
    }

}

三,同步方法(线程安全,但是比较耗性能,但是不具有 lazy 特性)

package test;

/**
 * @author Administrator 
 * 多线程变成单例模式——3
 */
public class SingletonTest {

    // 类加载是创建一个对象
    private static SingletonTest singleton = null;

    // 私有构造方法,防止被实例化
    private SingletonTest() {

    }

    // 获取单例对象 
    public static synchronized SingletonTest getInstance() { //同步方法块
        if(singleton == null){
            singleton = new SingletonTest();
        }

        return singleton;
    }

}

四,使用内部类方法(线程安全,lazy 特性)

package test;

/**
 * @author Administrator 
 * 多线程变成单例模式——4
 */
public class SingletonTest {

    // 私有构造方法,防止被实例化
    private SingletonTest() {

    }

    /* 内部类 */
    private static class SingletonFactory {
        private static SingletonTest single = new SingletonTest(); // 类加载是不会执行
    }

    /* 获取实例对象 */
    public static SingletonTest getInstance() {

        return SingletonTest.SingletonFactory.single;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值