Java单例模式的几种写法
来源:互联网 发布:ih5 知乎 编辑:程序博客网 时间:2024/04/30 12:32
第一种(懒汉,线程不安全):
1 public class Singleton {
2 private static Singleton instance;
3 private Singleton (){}
4 public static Singleton getInstance() {
5 if (instance == null) {
6 instance = new Singleton();
7 }
8 return instance;
9 }
10 }
11
这种写法lazy loading很明显,但是致命的是在多线程不能正常工作。2 private static Singleton instance;
3 private Singleton (){}
4 public static Singleton getInstance() {
5 if (instance == null) {
6 instance = new Singleton();
7 }
8 return instance;
9 }
10 }
11
第二种(懒汉,线程安全):
1 public class Singleton {
2 private static Singleton instance;
3 private Singleton (){}
4 public static synchronized Singleton getInstance() {
5 if (instance == null) {
6 instance = new Singleton();
7 }
8 return instance;
9 }
10 }
11
2 private static Singleton instance;
3 private Singleton (){}
4 public static synchronized Singleton getInstance() {
5 if (instance == null) {
6 instance = new Singleton();
7 }
8 return instance;
9 }
10 }
11
这种写法能够在多线程中很好的工作,而且看起来它也具备很好的lazy loading,但是,遗憾的是,效率很低,99%情况下不需要同步。
第三种(双重校验锁):
1 public class Singleton {
2 private volatile static Singleton singleton;
3 private Singleton (){}
4 public static Singleton getSingleton() {
5 if (singleton == null) {
6 synchronized (Singleton.class) {
7 if (singleton == null) {
8 singleton = new Singleton();
9 }
10 }
11 }
12 return singleton;
13 }
14 }
15
2 private volatile static Singleton singleton;
3 private Singleton (){}
4 public static Singleton getSingleton() {
5 if (singleton == null) {
6 synchronized (Singleton.class) {
7 if (singleton == null) {
8 singleton = new Singleton();
9 }
10 }
11 }
12 return singleton;
13 }
14 }
15
阅读全文
0 0
- Java单例模式几种写法
- Java单例模式的几种写法
- Java单例模式的几种写法详解
- java的单例模式几种写法
- Java:单例模式的几种写法
- Java单例模式的几种写法
- java单例模式的几种写法
- Java单例设计模式的几种写法
- Java单例模式的几种写法
- Java单例模式的几种写法
- java面试(1)单例模式的几种写法
- 单例模式的几种写法
- 单例模式的几种写法
- 单例模式的几种写法
- 单例模式的几种写法
- 单例模式的几种写法
- 单例模式的几种写法
- 单例模式的几种写法
- Zookeep启动异常:Error contacting service. It is probably not running.
- PCL编译安装
- C#---将字符串按空格分隔
- 分冶--区间合并
- 购物车之 全选 反选 批量删除 包邮 总价
- Java单例模式的几种写法
- Windows 环境下使用 GCC
- django引入现有数据库
- 设计模式简介
- swift字符串,数组,字典和集合的遍历
- Chrome内核解析 -- 背景篇:Chromium的多进程多线程构架
- 自配料的误区,最好搭配净霉宝哦
- Selenium学习笔记21_CSS Selector
- Android属性动画