单例模式实现方式最常见的有三种:
1)懒汉式
2)饿汉式
3)双重锁式
/**
*
* @author: muyichun
* @date : 2016年3月22日10:49:47
* @function: 单例模式
*/
public class Main implements Runnable{
public static void main(String[] args) throws Exception {
Main m1 = new Main();
Main m2 = new Main();
Main m3 = new Main();
Main m4 = new Main();
Main m5 = new Main();
Main m6 = new Main();
Main m7 = new Main();
Main m8 = new Main();
Main m9 = new Main();
Main m10 = new Main();
m1.run();
m2.run();
m3.run();
m4.run();
m5.run();
m6.run();
m7.run();
m8.run();
m9.run();
m10.run();
}
@Override
public void run() {
Singleton s = Singleton.getInstance();
System.out.println(s);
}
}
/**
* 单例模式
*/
class Singleton{
private volatile static Singleton instance = null; //null延迟加载
private Singleton(){}; //防止被实例化
public static Singleton getInstance(){
if (null == instance) {
synchronized (Singleton.class) {
if (instance == null) instance = new Singleton();
}
}
return instance;
}
/* 如果该对象被用于序列化,可以保证对象在序列化前后保持一致 */
public Object readResolve() {
return getInstance();
}
}
贴上自己喜欢的代码方式!