Purpose:
In the single-piece mode, you must control the instance creation process to ensure that all the customer programs use the same instance created.
Notes
1. synchronization problems caused by lazy initialization:
Singleton class, used sleep to enlarge the problem.
package com.jue.singleton;public class Singleton {private static Singleton instance;private static int index = 0;private Singleton() {System.out.println("-------------------------index: " + (index++));}public static Singleton getInstance() {if (instance == null) {try{Thread.sleep(1000);}catch(Exception e){}instance = new Singleton();}return instance;}}
Mythread class
package com.jue.singleton;public class MyThread implements Runnable{@Overridepublic void run() {// TODO Auto-generated method stubSystem.out.println("MyThread run()");Singleton myInstance = Singleton.getInstance();}}
Main method:
package com.jue.singleton;public class TestSingleton {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubnew Thread(new MyThread()).start();Singleton instance = Singleton.getInstance();}}
Result:
Mythread run ()
------------------------- Index: 0
------------------------- Index: 1
Solution
A. Lock
public static synchronized Singleton getInstance() {if (instance == null) {try{Thread.sleep(1000);}catch(Exception e){}instance = new Singleton();}return instance;}
B. It is created during initialization.
private static Singleton instance = new Singleton();private static int index = 0;private Singleton() {System.out.println("-------------------------index: " + (index++));}public static Singleton getInstance() {return instance;}