代码文件目录:
初始版本:
java
复制代码
package Chapter5_SingletonPattern.origin;
/**
* @Author 竹心
* @Date 2023/8/5
**/
public class Singleton {
private static Singleton uniqueInstance;
private Singleton(){}
public static Singleton getInstance(){
if(uniqueInstance == null){
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
//问题:多线程中会出现多个实例被创建的情况
//other functions
}
三种解决多线程问题的方法:
java
复制代码
package Chapter5_SingletonPattern.Multithread;
import Chapter5_SingletonPattern.origin.Singleton;
/**
* @Author 竹心
* @Date 2023/8/5
**/
public class Singleton1 {
private static Singleton1 uniqueInstance;
private Singleton1(){}
//使用synchronized迫使每个线程进入此方法之前必须轮到他
//但是这样会导致性能开销大
public static synchronized Singleton1 getInstance(){
if(uniqueInstance == null){
uniqueInstance = new Singleton1();
}
return uniqueInstance;
}
//other functions
}
java
复制代码
package Chapter5_SingletonPattern.Multithread;
/**
* @Author 竹心
* @Date 2023/8/5
**/
public class Singleton2 {
//急切创建实例:在静态初始化器中就创建实例
private static Singleton2 uniqueInstance = new Singleton2();
private Singleton2(){}
public static Singleton2 getInstance(){
return uniqueInstance;
}
//other functions
}
java
复制代码
package Chapter5_SingletonPattern.Multithread;
import Chapter5_SingletonPattern.origin.Singleton;
/**
* @Author 竹心
* @Date 2023/8/5
**/
public class Singleton3 {
//用双重检查加锁减少使用同步,降低开销
private volatile static Singleton3 uniqueInstance;
//volatile保证uniqueInstance为单实例类的时候多个线程正确处理
private Singleton3(){}
public static Singleton3 getInstance(){
if(uniqueInstance == null){
synchronized (Singleton3.class){
if(uniqueInstance == null){//进入同步区块后,再检查一次
uniqueInstance = new Singleton3();
}
}
}
return uniqueInstance;
}
}
Notes:
复制代码
单件模式:
确保一个类只有一个实例,并提供一个全局的访问点