//饿汉式
class Single{
private static final Single s=new Single();
private Single(){}
public static Single getInstance(){
return s;
}
}
//懒汉式
class Single{
private static s=null;
private Single(){}
public static Single getInstance(){
if(s==null){//防止加同步降低效率 必须等于Null再判断同步
synchronized(Single.class){//防止多线程出现问题
if(s==null)
//->0 ->1 线程到这里被切换 会new 多个对象 所以要加同步
s=new Single();
return s;
}
}
}
}
Java 同步单例设计模式
最新推荐文章于 2024-06-12 16:46:06 发布