单例模式有两种:饿汉模式和懒汉模式,懒汉模式的特点是延迟加载实例
//饿汉模式
class Singleton1{
private static final Singleton1 instance = new Singleton1();
private Singleton1(){}
public static Singleton1 getSingleton()
{
return instance;
}
}
//懒汉模式
class Singleton2{
private static Singleton2 instance;
private Singleton2(){}
public static Singleton2 getSingleton()
{
if(instance == null)
instance = new Singleton2();
return instance;
}
}
懒汉模式在多线程的情况下,会存在安全问题,对象会被实例化多次,可以用同步方法或者同步方法快的方式解决
//解决懒汉模式多线程的安全问题
class Singleton3{
private static Singleton3 instance;
private Singleton3(){}
public static synchronized Singleton3 getSingleton()
{
if(instance == null)
instance = new Singleton3();
return instance;
}
}
但是这种方式由于增加了判断锁的操作,会使得执行效率变慢
//解决懒汉模式多线程的安全问题的优化方案
class Singleton4{
private static Singleton4 instance;
private Singleton4(){}
public static Singleton4 getSingleton()
{
if(instance == null)
{
synchronized(Singleton4.class)
{
if(instance == null)
instance = new Singleton4();
}
}
return instance;
}
}
继续阅读与本文标签相同的文章
hadoop--hive数据仓库
-
Learning algorithem the hard way array (part 2)
2026-05-17栏目: 教程
-
阿里云原生数据库POLARDB当选世界互联网领先科技成果
2026-05-17栏目: 教程
-
阿里云服务器ECS + tomcat + 域名解析 部署web页面
2026-05-17栏目: 教程
-
为青年创业打开梦想之窗——中国“互联网+”大学生创新创业大赛五年综述
2026-05-17栏目: 教程
-
重磅 | 云原生数据库崛起,阿里云POLARDB当选世界互联网领先科技成果!
2026-05-17栏目: 教程
