一、双检锁(Double Check Locking)

  1. package org.mlinge.s05;
  2. public class MySingleton {
  3. //使用volatile关键字保其可见性
  4. volatile private static MySingleton instance = null;
  5. private MySingleton(){}
  6. public static MySingleton getInstance() {
  7. try {
  8. if(instance != null){//懒汉式
  9. synchronized (MySingleton.class) {
  10. if(instance != null){//二次检查
  11. //执行操作
  12. }
  13. }
  14. }else{
  15. //创建实例之前可能会有一些准备性的耗时工作
  16. Thread.sleep(300);
  17. synchronized (MySingleton.class) {
  18. if(instance == null){//二次检查
  19. instance = new MySingleton();
  20. }
  21. }
  22. }
  23. } catch (InterruptedException e) {
  24. e.printStackTrace();
  25. }
  26. return instance;
  27. }
  28. }

二、使用静态内置类实现单例模式

  1. package org.mlinge.s06;
  2. public class MySingleton {
  3. //内部类
  4. private static class MySingletonHandler{
  5. private static MySingleton instance = new MySingleton();
  6. }
  7. private MySingleton(){}
  8. public static MySingleton getInstance() {
  9. return MySingletonHandler.instance;
  10. }
  11. }