单例模式:确保一个类最多只有一个实例,并提供一个全局访问点。
单例模式在多线程里面的优化:
①同步(synchronized) getInstance方法,缺点:耗资源多,优点:目的达到了
public class XXX { private static XXX instance; private XXX(){ super(); } public synchronized static XXX getInstance(){ if(instance==null){ instance=new XXX(); } return instance; } }
②“急切”创建实例
public class XXX { private static XXX instance = new XXX(); private XXX(){ super(); } public synchronized static XXX getInstance(){ return instance; } }
③双重检查加锁
public class XXX { private volatile static XXX instance; private XXX() { super(); } public static XXX getInstance() { if (instance == null) { synchronized (XXX.class) { instance = new XXX(); } } return instance; } }