Single-Case mode:
1PublicClassperson{2PublicStatic person per//Defines a static variable that is used to store the object of the current class3Private person ()//Structuring method Privatization4{5}6PublicStatic Person getinstance ()//Defines a static method that is used to obtain an instance of the current class7{8if (per==Null)9{10 per=this;11 }12 return this;13 }14 15 }16 public class Student{ 18 person per=person.getinstance (); call static method 19}
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!
1ClassPerson2{3Private person person=Null;4PrivatePerson () {}5PublicPerson getinstance ()6{7if (person==Null)8{9 person =NewPerson ();10}11ReturnPerson12}1314}*/15ClassPerson16{17Private person person=Null;18PrivatePerson () {}19PublicPerson getinstance ()20{21stif (person==Null)22{Synchronized (This)24{25if (person==Null)person =NewPerson ();2728}29}3051.Returnperson;31}32}33/*34*35* This allows multi-threaded control within the synchronized thread control block, and there will be no more multiple objects when multiple threads are accessed.36* And there's a person outside. ==null judgment is used to improve efficiency, or the first time to determine the lock, consumption of thick resources37* This can improve efficiency once in a while38 */39 public class single {40 public static void main (String args[]) 41 {42 system. "this is Java "); 43 }44}
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 case