java单例模式懒汉和饿汉

实现:

1 公开静态的对外访问方法

2 私有的构造方法(保证不被外部调用)

3 类加载时候创建对象

饿汉式:

public class Instance1 {

	// 饿汉式单例
	public static void main(String[] args) {

		Instance1 d1 = Instance1.getInstance1();
		Instance1 d2 = Instance1.getInstance1();

		if (d1 == d2 ) {
			System.out.println("====");
		}

	}

	private static Instance1 d = new Instance1();

	private Instance1() {
	}

	public static Instance1 getInstance1() {

		return d;
	}

}

懒汉式:

public class Instance2 {

	// 懒汉试
	public static void main(String[] args) {

		Instance2 d1 = Instance2.getInstance2();
		Instance2 d2 = Instance2.getInstance2();

		if (d1 == d2) {
			System.out.println("====");
		}

	}

	private static Instance2 d = null;

	private Instance2() {
	}

	public static Instance2 getInstance2() {
		 

		 

				if (d == null) {
					d = new Instance2();

			 
		}
		return d;
	}

}

 

懒汉式饿汉式有什么区别:

饿汉式 在类加载的时候对象就已经new出来,对内存开销比较大,不建议这样使用。

 

懒汉式 单线程下线程安全,一定是单例模式。

在多线程下一定就是安全的吗? 那可不一定?

ab两个线程同时在d==null这行代码位置时,容易产生两个对象,这样子无法保证单例模式了,所以应该采用加锁的方式进行同步。

	
	public static  synchronized  Instance2 getInstance2() {
		
		if(d == null) {
			d = new Instance2();
			
		}
		
		return d;
	}
	

以上代码,ab线程同时进入,必须等待一个线程释放之后另一个线程才能进入锁,这样子代码不是很高效(如果有一个线程一直处于未释放锁,那另一个线程会一直处于等待状态),所以采用双重锁进行判断。

public class Instance2 {

	// 懒汉试
	public static void main(String[] args) {

		Instance2 d1 = Instance2.getInstance2();
		Instance2 d2 = Instance2.getInstance2();

		if (d1 == d2) {
			System.out.println("====");
		}

	}

	private static Instance2 d = null;

	private Instance2() {
	}

	public static Instance2 getInstance2() {
		if (d == null) {

			synchronized (Instance2.class) {

				if (d == null) {
					d = new Instance2();

				}

			}
		}
		return d;
	}

}

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
单例模式是一种设计模式,用于确保一个类只有一个实例,并提供一个全局访问点来获取该实例。在单例模式中,懒汉饿是两种常见的实现方式。 1. 懒汉模式: 懒汉模式是指在需要使用实例时才创建对象。以下是懒汉模式的代码示例: ```java public class Singleton { private static Singleton instance; private Singleton() { // 私有构造函数 } public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } ``` 在懒汉模式中,通过一个静态变量`instance`来保存实例,初始值为null。在`getInstance()`方法中,首先检查`instance`是否为null,如果为null,则创建一个新的实例并赋值给`instance`,然后返回该实例。由于懒汉模式是线程安全的,因此在`getInstance()`方法上加了`synchronized`关键字,确保在多线程环境下只有一个线程可以创建实例。 2. 饿模式: 饿模式是指在类加载时就创建对象,无论是否使用该实例。以下是饿模式的代码示例: ```java public class Singleton { private static Singleton instance = new Singleton(); private Singleton() { // 私有构造函数 } public static Singleton getInstance() { return instance; } } ``` 在饿模式中,通过一个静态变量`instance`来保存实例,并在定义时就进行初始化。在`getInstance()`方法中,直接返回`instance`即可。由于饿模式在类加载时就创建了实例,因此不存在线程安全问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值