java单例模式并解决懒汉式下线程不安全的问题

单例模式中分为懒汉式和饿汉式

其中,懒汉式是线程不安全的,当有多条线程同时访问单例对象时,则会出现多线程临界资源问题。
现在用多线程实现并解决线程安全问题

饿汉式

public class SigletonDemo01 {
       static HashSet<King> hs = new HashSet<>();
       static Runnable r = new Runnable() {
	@Override
		public void run() {
		//获取单例对象
		King king = King.currentInstance();
		//将获取到的单例对象添加到集合中
		hs.add(king);
		}
	};
		public static void main(String[] args) {
		//需求:多条线程同时去获取单例对象,然后将获取到的单例对象添加到HashSet中
		//创建多个线程对象,同时访问 单例对象
		for (int i = 0; i < 10000; i++) {
		Thread thread = new Thread(r);
		thread.start();
		}
		System.out.println(hs);
		}
	}

懒汉式

public class SigletonDemo02 {
	    static HashSet<Queue> hs = new HashSet<>();
	    static Runnable r = new Runnable() {
		@Override
		public void run() {
			// 获取单例对象
			Queue king = Queue.currentInstance();
			// 将获取到的单例对象添加到集合中
			hs.add(king);
			}
		};
		public static void main(String[] args) {
			// 创建多个线程对象,同时访问 单例对象
			for (int i = 0; i < 1000; i++) {
			     Thread thread = new Thread(r);
			     thread.start();
			}
			System.out.println(hs);
		}
	}
	class Queue {
		private static Queue instance;
		private Queue() {
		}
		//使用同步代码块,同步方法,以及同步锁都可以解决
		public synchronized static Queue currentInstance() {
			if (instance == null) {
			instance = new Queue();
		}
		return instance;
		}
}

猜你喜欢

转载自blog.csdn.net/weixin_43345864/article/details/84797548