1 package com.atfu.java01;
2
3 /**
4 * 使用同步的方式将单例模式中的懒汉式改写为线程安全的
5 *
6 * @author fu jingchao
7 * @creat 2021/10/18-21:47
8 */
9 public class BankTest {
10 public static void main(String[] args) {
11
12 }
13 }
14
15 class Bank{
16 private Bank(){
17
18 }
19 private static Bank instance = null;
20 public static Bank getInstance(){//静态方法的锁就是当前类本身
21 //方式一:效率稍差
22 // synchronized (Bank.class) {
23 // if(instance == null){
24 // instance = new Bank();
25 // }
26 // return instance;
27 // }
28 //方式二:
29 if(instance == null){
30
31 synchronized (Bank.class) {
32 if(instance == null){
33 instance = new Bank();
34 }
35 }
36 }
37 return instance;
38 }
39
40 }
此为本人学习笔记,若有错误,请不吝赐教