在Java中,要确保一个类只有一个实例,可以使用单例模式。getInstance()
方法是实现单例模式的关键。以下是一个简单的单例模式实现示例:
public class Singleton {
// 使用volatile关键字确保多线程环境下的正确性
private static volatile Singleton instance;
// 将构造方法设为私有,防止外部创建新的实例
private Singleton() {
// 防止通过反射创建多个实例
if (instance != null) {
throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
}
}
// 提供一个静态方法来获取唯一的实例
public static Singleton getInstance() {
// 双重检查锁定(Double-Checked Locking)确保线程安全
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
在这个示例中,我们使用了双重检查锁定(Double-Checked Locking)来确保在多线程环境下的线程安全。当instance
为null
时,我们进入同步块并再次检查instance
是否为null
。如果仍然为null
,则创建一个新的Singleton
实例。这样可以确保在多线程环境下只有一个实例被创建。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>