标签:class 单利 静态方法 turn get == zed 线程 饿汉式
创建单利模式常见的两种方法;
//饿汉式
class Single{
private static final Single s = new Single();
private Single(){};
public static Single getInstance(){
return s;
}
}
//懒汉式
class Single{
private static Single s = null;
private Single(){};
public static Single getInstance(){
if(s == null){
s = new Single();
}
return s;
}
}
//懒汉式 多线程的问题
class Single{
private static Single s = null;
private Single(){};
public static Single getInstance(){
if(s == null){
synchronized(Single.class){//静态方法所以 锁只能用类
if(s == null){
s = new Single();
}
}
}
return s;
}
}
标签:class 单利 静态方法 turn get == zed 线程 饿汉式
原文地址:https://www.cnblogs.com/chzlh/p/9265348.html