处理多线程----单例模式
1.当JVM加载到这个类的时候,马上创建一个实例
public class Singleton { private static Singleton uniqueInstance = new Singleton(); private Singleton() { } public static Singleton getInstance() { return uniqueInstance; } }
2.用"双重检查加锁",在getInstance()减少使用同步 (仅支持Java 1.6)
public class Singleton { private volatile Singleton _instance; private Singleton() { } public Singleton getInstance() { if(_instance == null) { synchronized (Singleton.class) { if(_instance == null) _instance = new Singleton(); } } return _instance; } }
不推荐方式
public synchronized Singleton getInstance() { if(_instance == null) { _instance = new Singleton(); } return _instance; }