public class LazySingleton{
private static LazySingleton singleton;
private LazySingleton(){
}
//synchronized 同步 当它用来修饰一个方法或者一个代码块的时候,能够保证在同一时刻最多只有一个线程执行该段代码。
public synchronized static LazySingleton getInstance{
if(singleton==null){
singleton = new LazySingleton();
}
return singleton;
}
}
private static LazySingleton singleton;
private LazySingleton(){
}
//synchronized 同步 当它用来修饰一个方法或者一个代码块的时候,能够保证在同一时刻最多只有一个线程执行该段代码。
public synchronized static LazySingleton getInstance{
if(singleton==null){
singleton = new LazySingleton();
}
return singleton;
}
}
懒汉式单例
本文介绍了一种懒汉式的单例模式实现方式。通过在静态方法中使用 synchronized 关键字来确保实例创建过程中的线程安全性。这种方式下,单例对象只有在第一次被请求时才会被创建。
1355

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



