相关代码
饿汉式代码示例:
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
懒汉式代码实例:
public class Singleton {
private static Singleton instance = null;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) { // 判断是否有必要用“锁”
synchronized ("haha") {
if (instance == null) { // 判断是否有必要创建对象
instance = new Singleton();
}
}
}
return instance;
}
}
文章介绍了Java中两种实现单例模式的方法:饿汉式和懒汉式。饿汉式在类加载时就完成了初始化,保证了线程安全但可能造成资源浪费;懒汉式在第一次调用时才创建实例,实现了按需加载,但在多线程环境下需要同步控制。
172万+

被折叠的 条评论
为什么被折叠?



