1. package com.atguigu.java2;
    2. /**
    3. * 使用同步机制将单例模式中的懒汉式改写为线程安全的
    4. *
    5. * @author Dxkstart
    6. * @create 2021-05-07 18:41
    7. */
    8. public class BankTest {
    9. public static void main(String[] args) {
    10. }
    11. }
    12. class Bank {
    13. private Bank() {
    14. }
    15. private static Bank instance = null;
    16. public static Bank getInstance() {
    17. //方式一:效率稍差
    18. // synchronized (Bank.class) {
    19. // if(instance == null){
    20. // instance = new Bank();
    21. // }
    22. // return instance;
    23. // }
    24. //方式二;效率更高
    25. if (instance == null) {
    26. synchronized (Bank.class) {
    27. if (instance == null) {
    28. instance = new Bank();
    29. }
    30. }
    31. }
    32. return instance;
    33. }
    34. }