singleton pattern
1. Concept
Hungry mode, lazy mode
2. Examples
package com.study.current.thread.day02; /** * Singleton, multi-threaded */ public class InnerSingleton { private static class Singletion{ private static Singletion single = new Singletion(); } public static Singletion getInstance(){ return Singletion.single; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } }
package com.study.current.thread.day02; import java.util.DuplicateFormatFlagsException; public class DoubleCheckDemo { private static DoubleCheckDemo dc ; public static DoubleCheckDemo getDc(){ if(dc == null){ try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace (); } synchronized (DoubleCheckDemo.class) { if(dc == null){ dc = new DoubleCheckDemo(); } } } return dc ; } /** * @param args */ public static void main(String[] args) { Thread t1 = new Thread(new Runnable() { public void run() { System.out.println(DoubleCheckDemo.getDc().hashCode()); } }); Thread t2 = new Thread(new Runnable() { public void run() { System.out.println(DoubleCheckDemo.getDc().hashCode()); } }); t1.start(); t2.start(); } }