Java实现五种单例模式

本文详细介绍了Java中五种单例模式的实现方式及其优缺点。包括懒汉式(非线程安全)、加锁同步的懒汉式(影响并发性能)、双重检查锁定的懒汉式(复杂易错)、饿汉式(启动慢但线程安全)以及静态内部类的单例模式(推荐,无锁且延迟加载)。每种模式都考虑了资源占用、启动效率和线程安全等因素。
摘要由CSDN通过智能技术生成

优点:懒加载启动快,资源占用小,使用时才实例化,无锁。
缺点:非线程安全。如果两个线程同时创建实例,依旧不能保证单例

public class Singleton1 {
	//私有的构造方法
	private Singleton1() {	
	}
	//私有的Singleton1属性
	private static Singleton1 singleton1 = null;
	//共有的方法  生成对象  
	public static Singleton1 getInstance() {
		if(singleton1 ==null) {
			singleton1 = new Singleton1();
		}
		return singleton1;
	}
}

优点:懒加载启动快,资源占用小,使用时才实例化,有锁
缺点:synchronized 为独占排他锁,并发性能差。
A加锁 B只能等待 等待队列会很长

  • 即使在创建成功以后,获取实例仍然是串行化操作。
public class Singleton2 {
	//私有的静态成员变量
	private static Singleton2 uniqueInstance = null;
	//私有化的构造方法
	private Singleton2() {
		
	}
	//共有的生成实例方法
	public static synchronized Singleton2 getInstance() {
		if(uniqueInstance ==null) {
			uniqueInstance = new Singleton2();
		}
		return uniqueInstance;
	}
}

优点:懒加载启动快,资源占用小&

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值