标签:
1 private Hashtable _ht = Hashtable.Synchronized(new Hashtable()); 2 static void Main(string[] args) 3 { 4 new Program().TestLock(); 5 Console.WriteLine($"主线程:{Thread.CurrentThread.ManagedThreadId}"); 6 Console.ReadKey(); 7 } 8 9 public void TestLock() 10 { 11 Task.Factory.StartNew(obj => SyncMethodA((string)obj), "laowang"); 12 Task.Factory.StartNew(obj => SyncMethodB((string)obj), "liupangzi"); 13 Thread.Sleep(6000); 14 Console.WriteLine($"输出值:{ _ht[0]}"); 15 } 16 17 18 private void SyncMethodA(string param) 19 { 20 Console.WriteLine($"方法A线程:{Thread.CurrentThread.ManagedThreadId}"); 21 lock (_ht.SyncRoot) 22 { 23 Thread.Sleep(5000); 24 _ht[0] = "SyncMethodA"; 25 Console.WriteLine($"A方法输出值:{ _ht[0]}"); 26 } 27 } 28 29 private void SyncMethodB(string param) 30 { 31 Console.WriteLine($"方法B线程:{Thread.CurrentThread.ManagedThreadId}"); 32 Console.WriteLine($"B方法输出值:{ _ht[0]}"); 33 _ht[0] = "SyncMethodB"; 34 }
标签:
原文地址:http://www.cnblogs.com/lanyuanbo/p/5857038.html