none
多线程下 获取 Object.GetHashCode() 值是否相等? RRS feed

  • 问题

  • 测试单件模式的代码
    
    
    
    
    public class Singleton {
    
    
    
    		private static Singleton instance;
    
    
    
    
    
    
    
    		// 私有的默认的构造函数,防止 默认的构造函数 被外部调用;
    
    
    
    		private Singleton() { }
    
    
    
    
    
    
    
    		/// <summary>
    
    
    
    		/// 获取一个 Singleton 模式的实例.
    
    
    
    		/// </summary>
    
    
    
    		public static Singleton Instance {
    
    
    
    			get {
    
    
    
    				if (instance == null) {
    
    
    
    					instance = new Singleton();
    
    
    
    				}
    
    
    
    				return Singleton.instance;
    
    
    
    			}
    
    
    
    		}
    
    
    
    	}
    
    
    
    

     

    下面是测试代码

    static private IList log = new List<Int32>();
    
    
    
    
    
    
    
    [TestMethod()]
    
    
    
    		public void InstanceTestByThread() {
    
    
    
    			int threadCount = 2;
    
    
    
    
    
    
    
    			// 创建一定数量的线程执行体
    
    
    
    			Thread[] threads = new Thread[threadCount];
    
    
    
    			for (int i = 0; i < threadCount; i++) {
    
    
    
    				ThreadStart work = new ThreadStart(
    
    
    
    					delegate {
    
    
    
    						Log.Add(Design_Pattern.Singleton.Single_Thread.Without_Parameters.Singleton.Instance.GetHashCode());
    
    
    
    					}
    
    
    
    				);
    
    
    
    				threads[i] = new Thread(work);
    
    
    
    			}
    
    
    
    			// 执行线程
    
    
    
    			foreach (Thread item in threads) {
    
    
    
    				Thread.Sleep(1000);
    
    
    
    				item.Start();
    
    
    
    			}
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    			for (int i = 0; i < threadCount - 1; i++) {
    
    
    
    				for (int j = i + 1; j < threadCount; j++) {
    
    
    
    					Assert.IsNotNull(SingletonTest.Log[i]);
    
    
    
    					Assert.IsNotNull(SingletonTest.Log[j]);
    
    
    
    					Assert.AreNotEqual(SingletonTest.Log[i], SingletonTest.Log[j]);
    
    
    
    				}
    
    
    
    			}
    
    
    
    		}
    
    
    
    


    2011年5月26日 13:01

答案

全部回复