/**
* 懒汉式,线程不安全
* @author lang
*
*/
public class Singleton {
private static Singleton instance;
private Singleton(){};
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();//假如A线程在此时刚好在进行new对象,而线程B
//刚刚好的走到instance == null 为true此时便有两个对象
}
return instance;
}
}
/**
* 懒汉,线程安全
* public class Singleton{
* private static Singleton instance;
* private Singleton(){};
* public static synchronized Singtelon getInstance(){
* if(instance == null){
* instance = new Singleton();
* }
* return instance;
* }
* }
*/
/**
* 饿汉式
*
* public class Singleton{
*
* private Singleton instance = new Singleton();
* private Singleton(){};
* public static Singleton getInstance(){
* return instance;
* }
* }
*/
优先考虑饿汉式,没有线程安全问题