单例模式的总结
来源:互联网 发布:数据备份方式 编辑:程序博客网 时间:2024/06/10 12:08
public class Instance { private Instance() { } // 1恶汉式 代码简单 但没有实现延迟加载,耗资源;并且线程不安全,当两条线程同时执行,会创建重复对象;// private static Instance instance=new Instance();// public static Instance getInstance(){// return instance;// }// 2懒汉式 代码简单 实现的延迟加载,但线程不安全,多线程时无法正常工作;// private static Instance instance=null;// public static Instance getInstance(){// if(instance==null){// instance=new Instance();// }// return instance;// }// 2.1懒汉式 线程安全 但是效率低;// private static Instance instance=null;// private static synchronized Instance getInstance(){// if(instance==null){// instance=new Instance();// }// return instance;// }// 3.双重校验锁 这种方式的好处在于在sychronized 之前添加了一次null检查,看似简单,但是他的添加,避免了不必要的加锁处理,提高了并发度,很大程度上提高了性能;// private static volatile Instance instance=null;//volatile 关键字让变量的对其他线程可见// public static Instance getInstance(){// if(instance==null){// synchronized (Instance.class){// if(instance==null){// instance=new Instance();// }// }// }// return instance;// } //4静态内部类的方式;这种方式实现了栏加载,因为Instance 加载后 单例对象并没有实例化,因为InstanceHolder没有被主动调用;// private static class InstanceHolder{// private static final Instance INSTANCE=new Instance();//}// public static Instance getinstanse(){// return InstanceHolder.INSTANCE;// } //5 枚举方法// enum SingletonDemo {// INSTANCE;//// public void otherMethods() {// System.out.println("Something");// }// }}
阅读全文
0 0
- 单例模式的总结
- 单例模式的总结
- 单例模式总结
- 单例模式总结
- 单例模式总结
- 单例模式总结
- 单例模式总结
- 单例模式总结
- 单例模式总结
- 单例模式总结
- 总结单例模式
- 单例模式总结
- 单例模式总结
- 单例模式总结
- 单例模式总结
- 单例模式总结
- java单例模式的小总结
- 单例设计模式的一点总结
- base64编码的由来及其运算
- 【C语言】n维数组的指针作为形参的方法
- 计算机与编程语言关系的简单介绍001
- hdu2883kebab (最大流+时间段离散+构图思维)
- [leetcode] 404. Sum of Left Leaves
- 单例模式的总结
- 头一次被黑!阿里云与腾讯云两台服务器数据库均被清空,比特币额
- Git客户端的常用配置
- LeetCode 34 Search for a Range
- Echarts 饼状图的标注 字体等样式修改
- SPOJ-1029 MATSUM
- b树,b+树,红黑树
- Fragment引起错误(待完成)
- 深度学习Day2(神经网络的基础编程)