对多线程下的单例模式的一点思考

1、首先看饿汉模式

    比较消耗内存。

代码如下:

/*饿汉式 单例模式*/
public class HungrySingleton {

    private HungrySingleton() {

    }

    private static final HungrySingleton HUNGRY=new HungrySingleton();

    public static HungrySingleton getInstance(){
        return HUNGRY;
    }
}

2、然后看懒汉模式

需要的时候再去new 对象。而且双锁保证线程安全。

代码如下:

/*
*懒汉式单例模式 为了保证线程安全
* */
public class TestSingleton {


    private TestSingleton() {
        System.out.println(Thread.currentThread()+"线程执行");
    }

    private volatile static TestSingleton testSingleton;

    public static TestSingleton getInstance() {
        if (testSingleton == null) {
            synchronized (TestSingleton.class){
                if (testSingleton == null) {
                    testSingleton=new TestSingleton();
                }
            }
        }

        return testSingleton;
    }

    public static void main(String[] args) {
        for ( int i = 0; i < 10; i++) {
            new Thread(()->{
                testSingleton.getInstance();

            }).start();
        }
    }
}

3、测试结果(双重锁后保证了线程安全和对象的唯一)

Thread[Thread-0,5,main]线程执行

全部评论

相关推荐

05-09 12:23
已编辑
华南理工大学 Java
野猪不是猪🐗:给他装的,双九+有实习的能看的上这种厂我直接吃⑨✌们拿它练练面试愣是给他整出幻觉了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务