优点:懒加载启动快,资源占用小,使用时才实例化,无锁。
缺点:非线程安全。如果两个线程同时创建实例,依旧不能保证单例
public class Singleton1 {
//私有的构造方法
private Singleton1() {
}
//私有的Singleton1属性
private static Singleton1 singleton1 = null;
//共有的方法 生成对象
public static Singleton1 getInstance() {
if(singleton1 ==null) {
singleton1 = new Singleton1();
}
return singleton1;
}
}
优点:懒加载启动快,资源占用小,使用时才实例化,有锁
缺点:synchronized 为独占排他锁,并发性能差。
A加锁 B只能等待 等待队列会很长
- 即使在创建成功以后,获取实例仍然是串行化操作。
public class Singleton2 {
//私有的静态成员变量
private static Singleton2 uniqueInstance = null;
//私有化的构造方法
private Singleton2() {
}
//共有的生成实例方法
public static synchronized Singleton2 getInstance() {
if(uniqueInstance ==null) {
uniqueInstance = new Singleton2();
}
return uniqueInstance;
}
}
优点:懒加载启动快,资源占用小&