[size=large]教科书中的单例模式的描述好些都没注意线程安全,很两个线程同时去创造实例,这样就能够产生两个实例,正确写法如下:
public class Singleton(){
private volatile static Singleton singleton;
private Sington(){};
public static Singleton getInstance(){
if(singleton == null){
synchronized (Singleton.class);
if(singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
}
volatile在jdk 1.5以上才能使用---代码源于《head first设计模式》
http://www.blogjava.net/duduli/archive/2008/11/22/241945.html[/size]
public class Singleton(){
private volatile static Singleton singleton;
private Sington(){};
public static Singleton getInstance(){
if(singleton == null){
synchronized (Singleton.class);
if(singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
}
volatile在jdk 1.5以上才能使用---代码源于《head first设计模式》
http://www.blogjava.net/duduli/archive/2008/11/22/241945.html[/size]