目的:保证全局唯一
1.饿汉式
注:该方式下不会存在线程安全为题,但会提前创建对象。
class Singleton {
private static final Singleton singelton = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return singelton;
}
}
2.懒汉式
注:可能存在线程安全问题。在使用的时候,才会创建对象,不会提前占有内存。
(1)此种方式会出现线程安全问题
class Singleton {
private static Singleton singelton;
private Singleton() {}
public static Singleton getInstance() {
if(singelton == null) { //当多个线程通过这个判断条件,会创建多个Singleton对象
singelton = new Singleton();
}
return singelton;
}
}
(2)通过在方法上使用synchronized实现线程安全,但是锁的粒度太大
class Singleton {
private static Singleton singelton;
private Singleton() {}
public static synchronized Singleton getInstance() {
if(singelton == null) {
singelton = new Singleton();
}
return singelton;
}
}
(3)在方法内使用synchronized 【锁双重检查】
class Singleton {
private static Singleton singelton;
private Singleton() {}
public static Singleton getInstance() {
if(singelton == null) {
synchronized (Singleton.class) { // 此处锁住整个类对象, 如果里面没有其他方法,可以采用这种方式
if(singelton == null) { //此处采用 锁双重检查
singelton = new Singleton();
}
}
}
return singelton;
}
}