饿汉式
好处:线程安全
坏处:一开始就占用了一块内存空间
class A{//饿汉式,线程安全,但一开始就造好了对象,占用内存空间
private A(){}
static A a = new A();
static public A getInstance(){
return a;
}
}
懒汉式
好处:节省内存,等到使用时猜造对象
坏处:线程不安全
class B{//懒汉式,线程不安全,
private B(){}
static B b = null;
static public B getIntance(){
if(b==null){//如果一个线程在此阻塞,另外一个线程进入早造了一个B对象,等到原线程苏醒又会造一个新的对象
b = new B();
}
return b;
}
}
懒汉式在方法上加synchronized 改进后变为线程安全:
class B{//懒汉式,改进后线程安全
private B(){}
static B b = null;
static synchronized public B getIntance(){
if(b==null){
b = new B();
}
return b;
}
}