自己黑自己做的网站,有什么做网兼的网站,青岛seo精灵,设计都有什么设计系列文章目录 【设计模式】之责任链模式【设计模式】之策略模式【设计模式】之模板方法模式 文章目录 系列文章目录 前言 一、什么是单例模式 二、如何使用单例模式 1.单线程使用 2.多线程使用#xff08;一#xff09; 3.多线程使用#xff08;二#xff09; 4.多线程使用…系列文章目录 【设计模式】之责任链模式【设计模式】之策略模式【设计模式】之模板方法模式 文章目录 系列文章目录 前言 一、什么是单例模式 二、如何使用单例模式 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*/
虽然添加 synchronized 可以在多线程下保证实例化一次对象但是因为加锁会造成系统资源浪费。假设我们遍历10次相当经过多次经过锁而我们只需要保证第一次实例化成功也就是加一次锁后面的会经过逻辑判断不会实例化对象。因此我们引出了下面一种方法。 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;}
} 总结
以上就是单例模式在单多线程下的使用以及优化今天就先介绍到这里我们下期再见。✋