小例子
package net.xdclass;
public class SingletonLazy {
private static SingletonLazy instance;
/**
* 构造函数私有化
*/
private SingletonLazy(){}
/**
* 单例对象的方法
*/
public void process(){
System.out.println("方法调用成功");
}
/**
* 第一种方式
* 对外暴露一个方法获取类的对象
*
* 线程不安全,多线程下存在安全问题
*
*/
// public static SingletonLazy getInstance(){
// if(instance == null){
// instance = new SingletonLazy();
// }
// return instance;
// }
/**
* 第二种实现方式
* 通过加锁 synchronized 保证单例
*
* 采用synchronized 对方法加锁有很大的性能开销
*
* 解决办法:锁粒度不要这么大
*
* @return
*/
// public static synchronized SingletonLazy getInstance(){
// if(instance == null){
// instance = new SingletonLazy();
// }
// return instance;
// }
/**
* 第三种实现方式
* @return
*/
public static SingletonLazy getInstance(){
if(instance == null){
// A、B
synchronized (SingletonLazy.class){
instance = new SingletonLazy();
}
}
return instance;
}
}
SingletonLazy.getInstance().process();
控制台输出


本文作者为DBC,转载请注明。