Singleton design pattern of the lazy formula (thread-safe)

Package Penalty for com.waibizi.demo04; 


/ ** 
 * lazy style of writing thread-safe 
 * Pros: solve the problem of thread-safe 
 * Cons: too inefficient, and want to get in each thread instance of the class when the execution getInstance () synchronization method should be carried out, but in fact, this method is only executed once instantiation code on it, time to get back want instances of the class 
 * direct return to the 
 * Conclusion: not recommended such an approach in the actual development 
 * @ author crooked nose 
 * 
 * / 
public  class Singleton_pattern { 

    public  static  void main (String [] args) {
         // the TODO Auto-Generated Method Stub 
        the Singleton Test = Singleton.getInstance (); 
        the Singleton test1 = Singleton.getInstance (); 
        the System.out .println (test.hashCode ());
        System.out.println (test1.hashCode ()); 

    } 

} 
@SuppressWarnings ( "All" )
 class the Singleton {
     Private  static the Singleton instance;
     Private the Singleton () { 
        
    } 
    
    // provides a public static method, when using this method before going to create instance
     // that lazy man's load (thread-safe) 
    public  static  the synchronized Singleton getInstance () {
         IF (instance == null ) { 
            System.out.println ( "I only initialized this time oh" ); 
            instance = new new the Singleton (); 
        } 
        return instance; 
    } 
}

Guess you like

Origin www.cnblogs.com/waibizi/p/12079849.html