Single-Case mode:
Public classperson{ Public Staticperson per;//defines a static variable that is used to store the object of the current class PrivatePerson ()//constructs a private method{} Public StaticPerson getinstance ()//defines a static method that holds an instance of the class{ if(per==NULL) {per= This;} return This;} Public classstudent{person per=persion.getinstance ();//calling a static method} }
I. How do I use multithreaded singleton mode?
First we need to know which of the two singleton modes are:
1. Lazy mode: Do not create an instance when the class is loaded, create a class when the call is run!
Advantages: fast loading speed!
Cons: When searching for stars, past objects are slow!
2. A hungry man mode: When the class is loaded, the initial work is done, so the loading speed is slow, but the speed of getting the object at runtime is fast!
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 < Span style= "color: #0000ff;" >class single {40 public static void main (string args[]) {42 system. Out.println ( "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!) )
A singleton pattern in Java