HashTable中的线程同步

 

使用 Hashtable.Synchronized包装的HashTable,针对多个写线程,或者多个读线程是线程安全的,但是针对又有度线程,又有写情况,是不安全的。Hashtable table2 = Hashtable.Synchronized(new Hashtable());//线程安全的。使用Lock(table2)也是一样的情况针对多个写线程,或者多个读线程是线程安全的,但是针对又有度线程,又有写情况,是不安全的。

 

要想对既有读线程又有写线程的情况是安全的需要使用SyncRoot属性,下面是示例代码:

class HashTableSync { private Hashtable table1 = new Hashtable();//不是线程安全的 private Hashtable table2 = Hashtable.Synchronized(new Hashtable());//线程安全的 public void IsSyncSafe() { Console.WriteLine("是否线程安全"+table1.IsSynchronized); Console.WriteLine("是否线程安全" + table2.IsSynchronized); // table1 = Hashtable.Synchronized(table1); Console.WriteLine("是否线程安全" + table1.IsSynchronized);// } private void WriteTable1() { lock (table1.SyncRoot) { Console.WriteLine("go into Writetable1"); for (int i = 0; i < 10; i++) { table1.Add(i, i); Console.WriteLine(i); Thread.Sleep(500); } Console.WriteLine("exit from Writetable1"); } } private void WriteTable2() { lock (table1.SyncRoot) { Console.WriteLine("go into Writetable2"); for (int i = 10; i < 20; i++) { table1.Add(i, i); Console.WriteLine(i); Thread.Sleep(500); } Console.WriteLine("exit from Writetable2"); } } private void ReadTable1() { lock (table1.SyncRoot) { Console.WriteLine("go into ReadTable1"); foreach (object a in table1) { Console.WriteLine(a.ToString()); Thread.Sleep(500); } } Console.WriteLine("exit from ReadTable1"); } public void SyncTest2() { Thread tWrite1 = new Thread(WriteTable1); Thread tWrite2 = new Thread(WriteTable2); Thread tRead1= new Thread(ReadTable1); Thread tRead2 = new Thread(ReadTable1); tWrite1.Start(); tRead2.Start(); tWrite2.Start(); tRead1.Start(); } } 

你可能感兴趣的:(C#.NET)