java线程中的单例模式的了解
package Thread;
//单例模式:在多线程的环境下 对外存在一个对象
//1.构造器私有化 避免外部new构造器
//2.提供私有的静态属性 存储对象的地址
//3.提供公共的静态方法 获取属性
public class TestDCL {
//2.提供私有的静态属性
private static TestDCL instance;
//1.构造器私有化
private TestDCL(){
}
//3.提供公共的静态方法
public static TestDCL getinstance() {
//再次检测
if(null != instance) {//避免不必要的同步s
return instance;
}
synchronized(TestDCL.class) {
if(null == instance) {
instance = new TestDCL();
}
}
return instance;
}
public static void main(String[] args) {
Thread t = new Thread();
System.out.println(TestDCL.getinstance());
t.start();
System.out.println(TestDCL.getinstance());
}
}
这篇博客介绍了Java中实现线程安全的单例模式。通过私有构造器、静态属性以及双重检查锁定(DCL)来确保在多线程环境下只有一个实例存在。主要代码展示了如何使用同步块在类初始化时创建单例对象。
1485

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



