Article From:https://www.cnblogs.com/1214045596js/p/9219092.html

The single example is divided into starving and slacker, and the single class is characterized by ensuring that a class can only implement an instance, instantiate it by itself and provide this example to the whole system.

Starving is when the class is loaded, it has already instantiated itself and thread is secure.

The code of the starving Chinese is as follows:

public class EHanSignle {
    //Private static class variable
    private static final EHanSignle eHanSignle = new EHanSignle();
    
    //The private construction method can only be instantiated inside the class.
    private EHanSignle() {}
    
    //Public static method. Class call
    public static EHanSignle getInstance() {
        return eHanSignle;
    }
}

 

Lazy style is the first instantiation of the method to instantiate itself.

Slacker code (thread insecurity) as shown below

public class LHanSignle {
    private static LHanSignle lHanSignle = null;
    private LHanSignle() {}
    
    public static LHanSignle getInstance() {
        if(lHanSignle == null) {
            lHanSignle = new LHanSignle(); 
        }
        return lHanSignle;
    }
}

There are three ways to achieve thread security:

The first is to add synchronization to the getInstance method.

public class LHanSignle {
    private static LHanSignle lHanSignle = null;
    private LHanSignle() {}
    
    public static synchronized LHanSignle getInstance() {
        if(lHanSignle == null) {
            lHanSignle = new LHanSignle(); 
        }
        return lHanSignle;
    }
}

The second is double check lock

public class LHanSignle {
    private static LHanSignle lHanSignle = null;
    private LHanSignle() {}
    
    public static LHanSignle getInstance() {  
        if (lHanSignle == null) {    
            synchronized (LHanSignle.class) {    
               if (lHanSignle == null) {    
                  lHanSignle = new LHanSignle();   
               }    
            }    
        }    
        return lHanSignle;   
    }  
}

The third method is static internal class (recommended):

public class LHanSignle {
    private static class loadClass{
        private static final LHanSignle lHanSignal = new LHanSignle();
    }
    private LHanSignle() {}
    
    public static LHanSignle getInstance() {  
        return loadClass.lHanSignal; 
    }  
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *