单例模式线程安全的实现方式

本文详细介绍了单例模式的多种实现方式,包括懒汉式线程不安全、懒汉式线程安全、双重检验锁、饿汉式static final、静态内部类形式及枚举创建等,并分析了每种实现的特点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package singleton;


//懒汉式线程不安全
public class Singleton {
private static Singleton singleton;
private Singleton() {
}
public static Singleton getInstance(){
if (singleton==null) {
singleton=new Singleton();
}
return singleton;
}
}


//懒汉式线程安全  效率不高因为在任何时候只能有一个线程调用getInstance()方法
class Singleton1 {
private static Singleton1 singleton1;
private Singleton1() {
}

public synchronized static Singleton1 getInstance(){
if (singleton1==null) {
singleton1=new Singleton1();
}
return singleton1;
}
}


//双重检验锁
class Singleton2 {
//volatile禁止指令重排序优化
private static volatile Singleton2 singleton2;
private Singleton2() {
}
public static Singleton2 getInstance(){
if (singleton2==null) {//一次检查
synchronized (Singleton.class) {
if (singleton2==null) {//二次检查
singleton2=new Singleton2();
}
}
}
return singleton2;
}
}


//饿汉式static final
class Singleton3 {
//类加载时即被初始化所有创建本身是实例安全的
private static  final Singleton3 singleton3=new Singleton3();
private Singleton3() {
}
public static Singleton3 getInstance(){

return singleton3;
}
}


//静态内部类的形式  推荐
class Singleton4 {
//类加载时即被初始化所有创建本身是实例安全的
private static class SingletonHolder{
private static final Singleton4 SINGLETON4=new Singleton4();
}
private Singleton4() {
}
public static Singleton4 getInstance(){
return SingletonHolder.SINGLETON4;//由于是私有静态内部类所以是懒汉式的加载
}
}


//枚举创建线程默认是线程安全的防止反序列化导致的重新创建对象
enum Singleton5{
INSTANCE;

}

参考文章http://wuchong.me/blog/2014/08/28/how-to-correctly-write-singleton-pattern/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值