package com.waibizi.demo03; /** * Pros: effect played lazy loading, but can only be used in single-threaded case * Cons: If it is a multi-threaded, a thread has entered if (instance == null) but have not had time to instantiate, this time another thread has entered if (instance == null), then it will generate more than instances * You can not use this lazy man's load in the case of multi-threaded * @Author crooked nose * */ @SuppressWarnings("all") public class Singleton_Pattern { public static void main(String[] args) { // TODO Auto-generated method stub Singleton test = Singleton.getInstance(); Singleton test1 = Singleton.getInstance(); System.out.println(test.hashCode()); System.out.println(test1.hashCode()); } } @SuppressWarnings("all") class Singleton{ private static Singleton instance; private Singleton() { } // provides a public static method, when this method is used only to create instance // i.e. lazy loading of formula public static the Singleton the getInstance () { IF (instance == null ) { System.out.println ( "I only initialized this time oh" ); instance=new Singleton(); } return instance; } }
Singleton design pattern of the lazy formula (thread-safe)
Guess you like
Origin www.cnblogs.com/waibizi/p/12079669.html
Recommended
Ranking