单例模式中的线程安全问题

package com.qianfeng.test;

public class Demo {
	public static void main(String[] args) {
		Test test = new Test();
		Thread thread = new Thread(test);
		thread.start();
	}

}
//单例模式三要素:
// 1.私有的构造方法
// 2.指向自己实例的私有静态引用
// 3.以自己的实例为返回值的静态的公有的方法
// 饿汉式
class Singleton {
	private static Singleton singleton = new Singleton();// 指向自己实例的私有静态引用
	private Singleton() {
	}// 私有的构造方法
	public static Singleton getSingleton() {// 以自己实例为返回值的静态的公有的方法
		return singleton;//这里只有一行代码,不会发生线程安全问题
	}
}

// 懒汉式
class Singleton1 {
	private static Singleton1 singleton = null;
	private Singleton1() {
	}// 私有的构造方法
	public static Singleton1 getSingleton() {
		if (singleton == null) {//目的:尽量减少线程安全代码的判断次数
			synchronized (Singleton1.class) {
				// synchronized (Object.class)
				if (singleton == null) {
					singleton = new Singleton1();
				}
			}
		}
		return singleton;
	}
}
class Test implements Runnable{
	public void run(){
		Singleton singleton = Singleton.getSingleton();
	}
}

猜你喜欢

转载自blog.csdn.net/qq_35334203/article/details/81742827