阅读量:4
这是一个使用懒汉式实现的Java单例模式代码示例:
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;
}
// 示例方法
public void showMessage() {
System.out.println("Hello, I'm a singleton!");
}
}
这是一个使用饿汉式实现的Java单例模式代码示例:
public class Singleton {
// 使用volatile关键字确保多线程环境下的正确性
private static final Singleton instance = new Singleton();
// 将构造方法私有化,防止外部实例化
private Singleton() {
// 防止通过反射创建多个实例
if (instance != null) {
throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
}
}
// 提供一个静态方法来获取唯一的实例
public static Singleton getInstance() {
return instance;
}
// 示例方法
public void showMessage() {
System.out.println("Hello, I'm a singleton!");
}
}
这两种实现方式都可以确保在多线程环境下只创建一个实例。你可以根据自己的需求选择合适的实现方式。
以上就是关于“java单例模式代码示例给”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm