目的:
单件模式要做的是通过控制实例的创建过程,确保客户程序使用的都是创建好的同一个实例。
需要注意的问题
1.Lazy初始化,引起的同步问题:
Singleton 类,通过sleep放大了问题的发生情况。
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类
package com.jue.singleton;
public class MyThread implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("MyThread run()");
Singleton myInstance = Singleton.getInstance();
}
}
main方法:
package com.jue.singleton;
public class TestSingleton {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new Thread(new MyThread()).start();
Singleton instance = Singleton.getInstance();
}
}
MyThread run()
-------------------------index: 0
-------------------------index: 1
解决的方法
a.加锁
public static synchronized Singleton getInstance() {
if (instance == null) {
try{
Thread.sleep(1000);
}catch(Exception e){}
instance = new Singleton();
}
return instance;
}
b.初始化的时候就创建。
private static Singleton instance = new Singleton();
private static int index = 0;
private Singleton() {
System.out.println("-------------------------index: " + (index++));
}
public static Singleton getInstance() {
return instance;
}