6. Multithreaded singleton mode





The original singleton mode is no longer applicable in multithreaded environment, so what should I do?


(1) single instance mode of thread safety with double locking



(2) static initialization singleton mode



Direct instantiationSingletonObject inGetInstanceMethod_Instanceobject


We know that static members are initialized only once, that is to say_InstanceThe class is instantiated the first time it is accessed, soSingletonWhen the class is first accessed, it is doneSingletonClass is instantiated only once. In this way, the singleton mode in multithreaded environment can also be guaranteed.



Correction: Please note that the parameterless constructor of singleton in the figure should be declared as private!!!!!!!!!!!!!!!!!!!