//饿汉式
public class Singleton{
private static Singleton singleton = new Singleton ();
private Singleton (){}
public static Singleton getInstance(){return singletion;}
}
//懒汉式
public class Singleton{
private static Singleton singleton = null;
public static synchronized synchronized getInstance(){
if(singleton==null){
singleton = new Singleton();
}
return singleton;
}
}
// * 总结
饿汉式是线程安全的,在类创建的同时就已经创建好一个静态的对象供系统使用,以后不在改变。
懒汉式如果在创建实例对象时不加上synchronized则会导致对对象的访问不是线程安全的。
推荐使用第一种的原因:从实现方式来讲他们最大的区别就是懒汉式是延时加载,
他是在需要的时候才创建对象,而饿汉式在虚拟机启动的时候就会创建。
饿汉式无需关注多线程问题、写法简单明了。
?
原文:http://zliguo.iteye.com/blog/2258879