java单例模式懒汉和饿汉

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38361347/article/details/81742507

实现:

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;
	}

}

猜你喜欢

转载自blog.csdn.net/weixin_38361347/article/details/81742507