JAVA single instance mode

wrong please point out


Single instance mode:

A class can have only one instance object

For example: a computer can have multiple print jobs, but only one is printing


package test;

/*
 * This is to initialize the object first.
 * Known as: Hungry Chinese
 * class Single {
	
	private Single() {
	}

	private static Single s = new Single();

	public static Single getInstance() {
		return s;
	}
}
 *
 *
 * */

//Use Hungry Chinese style when developing

// The object is initialized when the method is called, also known as the delayed loading of the object, called: lazy person
//Single class enters memory, the object does not exist yet, and the object is created only when the getInstance method is called
//Adding synchronized is to avoid that single instance objects may load multiple objects in memory, but the efficiency is low
//or as follows
//Finally, the hungry Chinese style is more practical;
class Single2{
	private static Single2 s=null;
	private Single2(){};
	/*
               method one
            public static synchronized Single2 getInstance(){
		if(s==null)
			s=new Single2();
		return s;
	}*/
           /*Method Two*/
	public static Single2 getInstance(){
		if(s==null){
			synchronized(Single.class){
				if(s==null)
					s=new Single2();
			}
		}
		return s;
	}
}

//It is recommended to use the hungry Chinese style when defining a singleton

If synchronization is not added, the situation of creating multiple instances may occur in multi-threading


After adding synchronized

Even if thread a waits after the if after the judgment, the b thread cannot enter the if judgment, and the a thread exclusively owns the second if judgment (for method 2)

                                                        

                                                                                        -------------------------By chick

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325724350&siteId=291194637