首先来明确一个问题,那就是在某些情况下,有些对象,我们只需要一个就可以了,

比如,一台计算机上可以连好几个打印机,但是这个计算机上的打印程序只能有一个,

这里就可以通过单例模式来避免两个打印作业同时输出到打印机中,

即在整个的打印过程中我只有一个打印程序的实例。

简单说来,单例模式(也叫单件模式)的作用就是保证在整个应用程序的生命周期中,

任何一个时刻,单例类的实例都只存在一个(当然也可以不存在)。

 

public class SingletonClass {

  private static SingletonClass instance = null;

  public static SingletonClass getInstance() {
if(instance == null) {
instance = new SingletonClass();
}
return instance;
} private SingletonClass() { } }

同步:

上面的代码很清楚,也很简单。然而就像那句名言:“80%的错误都是由20%代码优化引起的”。单线程下,这段代码没有什么问题,可是如果是多线程,麻烦就来了。我们来分析一下:
 

线程A希望使用SingletonClass,调用getInstance()方法。因为是第一次调用,A就发现instance是null的,于是它开始创建实例,就在这个时候,CPU发生时间片切换,线程B开始执行,它要使用SingletonClass,调用getInstance()方法,同样检测到instance是null——注意,这是在A检测完之后切换的,也就是说A并没有来得及创建对象——因此B开始创建。B创建完成后,切换到A继续执行,因为它已经检测完了,所以A不会再检测一遍,它会直接创建对象。这样,线程A和B各自拥有一个SingletonClass的对象——单例失败



public class SingletonClass {

  private static class SingletonClassInstance {
private static final SingletonClass instance = new SingletonClass();
} public static SingletonClass getInstance() {
return SingletonClassInstance.instance;
} private SingletonClass() { } }



最新文章

  1. Azure PowerShell (11) 使用自定义虚拟机镜像模板,创建Azure虚拟机并绑定公网IP(VIP)和内网IP(DIP)
  2. There is insufficient system memory to run this query 错误
  3. Leetcode Construct Binary Tree from Preorder and Inorder Traversal
  4. 蓝桥T291(BFS + 输出路径)
  5. sql学习资料
  6. C语言学习笔记--结构体
  7. xBIM 多个IFC文件合并
  8. Kafka Consumer
  9. 决策树系列(三)——ID3
  10. 元素的属性:client系列,scroll系列,offset系
  11. 解决ERR Client sent AUTH, but no password is set
  12. IntelliJ IDEA配置maven远程仓库
  13. AssetManager
  14. mybatis-config.xml
  15. zabbix3.4.7之Zabbix_Trigger_Function详解
  16. 自制“低奢内”CSS3登入表单,包含JS验证,请别嫌弃哦。
  17. CCNA学习与实验指南——第2章 网络互联和参考模型
  18. Linux终端执行shell脚本,提示权限不够的解决办法
  19. 2016年蓝桥杯B组C/C++省赛(预选赛)试题
  20. printf()的转换说明的修饰符中的标记、数字、和.数字

热门文章

  1. atCoder Ants on a Circle(又是蚂蚁问题。。。)
  2. noip模拟赛 捡金币
  3. Uva1103 Ancient Messages
  4. POJ 1523 SPF 割点 Tarjan
  5. MYSQL中有关表的简单操作
  6. Ubuntu 10.04.3 挂载NTFS移动硬盘
  7. [容斥原理] hdu 1796 How many integers can you find
  8. Java中的equals()和hashCode()
  9. PhoneGap3+版本号的安装、配置和使用[图]
  10. LeetCode 706. Design HashMap (设计哈希映射)