package model;
public class LazyMan {
public static void main(String[] args) {
System.out.println(LazyManExample.getInstance());
}
}
class LazyManExample{
//JIT或cpu可能会对指令进行重排序导致可能会使用到未初始化的实例,用volatile
//进行修饰
private volatile static LazyManExample instance;
public static LazyManExample getInstance(){
//双重判断保证不会发生线程同步问题
//懒汉模式
if(instance==null){
synchronized(LazyManExample.class){
if(instance==null){
instance=new LazyManExample();
}
}
}
return instance;
}
}
饿汉模式
1.只有真正主动使用对应的类的时候才会初始化
1.如当前启动类是main函数所在类
2.new操作
3.访问静态属性
4.访问静态方法
5.用反射访问该类
6.初始化一个类的子类
类成员变量整个过程只执行一次保证了线程安全
class HungrySingleton{
private static HungrySingleton instance=new HungrySingleton();
public static HungrySingleton getInstance(){
return instance;
}
}