1. /**
  2. * 一种错误的单例写法,线程不安全
  3. */
  4. private static Singleton uniqueSingleton;
  5. private Singleton() {
  6. }
  7. public static Singleton getInstance() {
  8. if (uniqueSingleton == null) {
  9. uniqueSingleton = new Singleton();
  10. }
  11. return uniqueSingleton;
  12. }
  1. /**
  2. * 线程安全的懒加载,影响效率,JVM不保证执行顺序
  3. */
  4. private static Singleton uniqueSingleton;
  5. private Singleton() {
  6. }
  7. public static synchronized Singleton getInstance() {
  8. if (uniqueSingleton == null) {
  9. uniqueSingleton = new Singleton();
  10. }
  11. return uniqueSingleton;
  12. }
  13. /**
  14. * 急加载模式,线程安全,代码简单
  15. */
  16. private final static Singleton singleton = new Singleton();
  17. private Singleton() {
  18. }
  19. public static Singleton getInstance() {
  20. return singleton;
  21. }
  22. /**
  23. * 懒加载,双重锁保证,线程安全
  24. */
  25. private static volatile Singleton singleton;
  26. private Singleton() {
  27. }
  28. private static Singleton getInstance() {
  29. if (singleton == null) {
  30. synchronized (Singleton.class) {
  31. if (singleton == null) {
  32. return new Singleton();
  33. }
  34. }
  35. }
  36. return singleton;
  37. }
  38. /**
  39. * 懒加载的内部类写法,线程安全,懒加载
  40. */
  41. private static class SingletonHolder {
  42. private final static Singleton singleton = new Singleton();
  43. }
  44. private Singleton() {
  45. }
  46. public static Singleton getInstance() {
  47. return SingletonHolder.singleton;
  48. }

版权声明:本文为batmand原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/batmand/p/8552920.html