常见两种写法:
饿汉式:
private A(){}//构造器私有
private static A instance=new A();
public static A getInstance(){
return instance;
}
懒汉式:
private A(){}//构造器私有
private static A instance=null;
public static A getInstance(){
if(instance==null){//因为只有当instance为空时,才可能存在线程安全问题(即其他线程新建了instance但是本线程判断instance为空)
synchronized(A.class){
if(instance==null){
instance=new A();}}}
return instance;
}
除此之外还有匿名内部类+枚举类
标签:Singleton,Pattern,private,instance,static,单例,线程,null From: https://www.cnblogs.com/java-source-learn/p/17142308.html