解决懒汉式线程安全问题
/**
-
Lazy singleton mode:
-
1. Only one object can be created, so the constructor must be privatized, and an object can only be created internally
-
2. The private static property saves the instantiated object to ensure that there is only one instantiated object in the memory
-
3. Determine whether the instantiated object is empty, if it is empty, use the privatization constructor to create an object
-
4. Both ways of synchronizing code blocks and synchronizing methods can solve the current thread safety problem
*/
class Bank
{ //Private static properties save Bank class objects private static Bank bank = null;//Private constructor to prevent Bank from creating objects outside the class
private Bank(){};//The public static method gets the only object of the Bank class
public static / synchronized / Bank getInstance()
{ if(bank == null) { synchronized (Bank.class) { if(bank == null) { / here if use synchronized other threads might wait here, once on a thread releases the lock, other threads will still execute the next line of code, it is still there will be security thread / / thread safety problems may arise back here
***** /
bank = new Bank();
}
}
}
return bank;
}
}