方式一:
public class Ins{ private Test test; public static synchronized Test getInstance(){ if(null == test){ test=new Test(); } return test; }}
问题:每次访问都会执行同步,消耗大
方式二:
public class Ins{ private volatile static Test test; //保证线程之间数据可见性。 public static Test getInstance(){ if(null == test){ synchronized(Ins.class){//同步类锁 if(null == test){ test=new Test(); } } } return test; }}