public class Singleton1 {//饿汉式
private Singleton1(){};
static Singleton1 singleton1 = new Singleton1();
public static Singleton1 getSingleton1(){
return singleton1;
}
}
public class Singleton2 {//懒汉式
private Singleton2(){};
static Singleton2 singleton2 = null;
public static Singleton2 getSingleton2(){
if (singleton2 == null){//如果不为null,不进入同步,加快效率
//如果为null,会有多个线程进入
synchronized(Singleton2.class){//多个线程进入此处,只有一个线程拿锁
if (singleton2 ==null){//只有一个线程new实例,其他线程跳出
singleton2 =new Singleton2();
}
}
}
return singleton2;
}
}
标签:模式,static,线程,单例,singleton2,Singleton2,Singleton1,null
From: https://www.cnblogs.com/exact/p/16879566.html