单线程中的单例模式:
public class Sinleton{
private volatile static Singleton instance;
private Singleton() {}
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
在多线程中使用单例模式:
public class Sinleton{
private volatile static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance(){ //只需要把getInstance方法编程同步的就可以了,可是这样
if(instance == null){ //会降低性能,所以可以使用下面的双重检查锁
instance = new Singleton();
}
return instance;
}
}
一个合格的单例模式
利用双重检查加锁:当创建instance实例为空时需要加锁,当instance创建出来之后则无需加锁,这样做的目可以大大的减小消耗.整个过程只加了一次锁.(因为同步锁非常耗时)
public class Sinleton{
private volatile static Singleton instance;
private Singleton() {}
public static Singleton getInstance(){
if(instance == null){
synchronized(Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
volatile关键字
1
2
3
4
|
XBYTE[2]=0x55;
XBYTE[2]=0x56;
XBYTE[2]=0x57;
XBYTE[2]=0x58;
|