Single-Case mode:
1 Public classperson{2 Public StaticPerson per//defines a static variable that is used to store the object of the current class3 PrivatePerson ()//Structuring Method Privatization4 {5 }6 Public StaticPerson getinstance ()//defines a static method that is used to obtain an instance of the current class7 {8 if(per==NULL)9 {TenPer= This; One } A return This; - } - the } - Public classstudent{ - -Person Per=person.getinstance ();//calling a static method +}
Thinking: How to implement the single-threaded mode?
First of all we need to know that the singleton is divided into two modes:
Lazy mode and Bad Han mode.
Lazy mode: When the class is loaded, the instance is not created and the class is created when the call is run. Advantages: fast loading speed! Cons: Get objects slow when running!
The above code is lazy, in line with multi-threaded single-case mode, but generally not used under multithreading!
A hungry man mode: When the class loads, the initialization is complete, so the class loads slowly. But it's faster to get objects at run time!
1 class Person2 {3PrivatePerson person=NULL;4PrivatePerson () {}5 PublicPerson getinstance ()6 {7if(person==NULL)8 {9person =NewPerson ();Ten } OnereturnPerson ; A } - -}*/ the class Person - { -PrivatePerson person=NULL; - PrivatePerson () {} + PublicPerson getinstance () - { +if(person==NULL) A { atSynchronized This) - { -if(person==NULL) -person =NewPerson (); - - } in } - Wuyi.returnPerson ; to } + } - /* the * * * This allows multi-threaded control within the synchronized thread control block, and there will be no more multiple objects when multiple threads are accessed. $ * And there's a person outside. ==null judgment is used to improve efficiency, or the first time to determine the lock, consumption of thick resourcesPanax Notoginseng * This can improve efficiency once in a while - * */ the PublicclassSingle { + Public StaticvoidMain (String args[]) A { theSystem. out. println ("This is Java"); + } -}
In the method of creating an instance there are two judgments, one-step lock. If the code enters into the first step of judging directly into judgment, multithreading who advanced who can get the object first. If the thread object is empty, give the object of the current class to it and continue waiting for the next process to enter. Due to the use of synchronized locking, you cannot enter multiple threads at the same time (queued form!) )
Java Single-instance mode