0
点赞
收藏
分享

微信扫一扫

第⑰讲:Ceph集群各组件的配置参数调整

alonwang 2024-05-02 阅读 13

系列文章目录


文章目录

系列文章目录

前言

一、什么是单例模式

二、如何使用单例模式

1.单线程使用

2.多线程使用(一)

3.多线程使用(二)

4.多线程使用(三)双重检测

总结


前言

今天给大家介绍23种设计模式中的单例模式,也是大家比较常见的一种设计模式,但是,里面的一些细节还是有很多人会忽略的。🌈


一、什么是单例模式

单例模式是指在内存中只会创建且仅创建一次对象的设计模式。在程序中多次使用同一个对象且作用相同时,为了防止频繁地创建对象使得内存飙升,单例模式可以让程序仅在内存中创建一个对象,让所有需要调用的地方都共享这一单例对象。

二、如何使用单例模式

1.单线程使用

这种方式只适合单线程下使用,多线程下会实例化多个对象,不一定是10个。

public class Single {
    private static Single instance;

    private Single(){
        System.out.println("实例化Single对象");
    }
    public static Single getInstance(){
        if (instance == null) instance = new Single();
        return instance;
    }
}

测试:

public class test {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            Single.getInstance();
        }
    }
}
测试结果:
    /*
    实例化Single对象
    Process finished with exit code 0
    */

2.多线程使用(一)

只需添加一个synchronized 关键字即可

public class Single {
    private static Single instance;

    private Single(){
        System.out.println("实例化Single对象");
    }
    public synchronized static Single getInstance(){
        if (instance == null) instance = new Single();
        return instance;
    }
}

测试:

public class test {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                Single.getInstance();
            }).start();
        }
    }
}
测试结果:
    /*
    实例化Single对象

    Process finished with exit code 0

    */

3.多线程使用(二)

在类加载的时候直接实例化对象。

public class Single {
    private static Single instance = new Single();

    private Single(){
        System.out.println("实例化Single对象");
    }
    public  static Single getInstance(){
        return instance;
    }
}

测试结果跟上方一样

4.多线程使用(三)双重检测

这种方式也能大大减少锁带来的性能消耗。

public class Single {
    private volatile static Single instance ;

    private Single(){
        System.out.println("实例化Single对象");
    }
    public static Single getInstance(){
        if (instance == null){
            synchronized (Single.class){
                if (instance == null){
                    instance = new Single();
                }
            }
        }
        return instance;
    }
}

总结

以上就是单例模式在单多线程下的使用以及优化,今天就先介绍到这里,我们下期再见。✋

举报

相关推荐

0 条评论