singleton 模式又称单例模式, 它能够保证只有一个实例. 在多线程环境中, 需要小心设计, 防止两个线程同时创建两个实例.

 

解法

1. 能在多线程中工作但效率不高

public sealed class Singleton2 {
	private Singleton2() {

	}

	private static readonly object synObj = new object();
	private static Singleton2 instance = NULL;

	public static Singleton2 instance {
		get{
			lock(synObj) {
				if(instance == NULL)
					instance = new Singleton2();
			}
			return instance;
		}
	}
}

  

上段代码低效在于每次获取 instance 时都会试图加上同步锁, 而加锁本身比较耗时, 应该尽量避免.

改进的方法是在加锁之前另外加一层判断

if(instance == NULL)

  

相关文章:

  • 2022-01-26
  • 2021-05-31
  • 2021-09-07
  • 2021-10-25
  • 2021-08-24
  • 2021-07-18
  • 2021-05-15
  • 2022-12-23
猜你喜欢
  • 2021-07-15
  • 2021-06-21
  • 2021-11-08
  • 2021-11-02
  • 2021-08-19
  • 2022-12-23
相关资源
相似解决方案