1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Collections.Concurrent; //引用命名空间 6 using System.Threading; 7 using System.Diagnostics; 8 using System.Threading.Tasks; 9 10 namespace 线程锁新概念 11 { 12 class Program 13 { 14 private static object obj = new object(); 15 16 private static Queue<Product> _queue = null; //一般队列Queue 17 private static ConcurrentQueue<Product> _currentQueue = null; //多线程安全下的队列 18 private static List<Task> taskList = new List<Task>(); 19 private static List<Task> curtaskList = new List<Task>(); 20 static void Main(string[] args) 21 { 22 //第一种并发执行 23 Thread.Sleep(1000); 24 _queue = new Queue<Product>(); 25 Stopwatch watch = new Stopwatch(); //统计时间消耗 26 watch.Start(); 27 for (int i = 0; i < 3; i++) 28 { 29 30 //Action actPro = new Action(AddProducts); //调用第一种方法 31 //IAsyncResult resultPro = actPro.BeginInvoke(null, null); 32 //actPro.EndInvoke(resultPro); 33 34 taskList.Add(Task.Factory.StartNew(AddProducts)); 35 36 } 37 //在等待之前这里还可以做别的事 38 Console.WriteLine("这里还可以做别的事儿。。。"); 39 40 Task.WaitAll(taskList.ToArray()); 41 watch.Stop(); 42 Console.WriteLine("当前数据量为{0}", _queue.Count); 43 Console.WriteLine("用lock锁的情况下使用时间为{0}", watch.ElapsedMilliseconds); 44 Console.WriteLine(); 45 46 //第二种并发执行 47 Thread.Sleep(1000); 48 _currentQueue = new ConcurrentQueue<Product>(); 49 Stopwatch watchCur = new Stopwatch(); 50 watchCur.Start(); 51 for (int i = 0; i < 3; i++) 52 { 53 //Action actCurpro = new Action(AddConcurrentProduct); //调用第二种方法 54 //IAsyncResult result = actCurpro.BeginInvoke(null, null); 55 //actCurpro.EndInvoke(result); 56 curtaskList.Add(Task.Factory.StartNew(AddConcurrentProduct)); 57 } 58 //在等待之前这里还可以做别的事 59 Console.WriteLine("这里还可以做别的事儿。。。"); 60 61 Task.WaitAll(curtaskList.ToArray()); 62 watchCur.Stop(); 63 Console.WriteLine("当前数据量为{0}", _currentQueue.Count); 64 Console.WriteLine("用ConcurrentQueue的情况下使用时间为{0}", watchCur.ElapsedMilliseconds); 65 Console.ReadLine(); 66 } 67 68 /// <summary> 69 /// 在lock加锁的情况下并行执行 70 /// </summary> 71 static void AddProducts() 72 { 73 Parallel.For(0, 30000, (i) => 74 { 75 Product product = new Product(); 76 product.Name = "name" + i; 77 product.Category = "Category" + i; 78 product.SellPrice = i; 79 lock (obj) 80 { 81 _queue.Enqueue(product); 82 } 83 }); 84 Console.WriteLine("当前线程ID为{0}", Thread.CurrentThread.ManagedThreadId); 85 } 86 87 /// <summary> 88 /// 在不加锁的情况下并行执行 89 /// </summary> 90 static void AddConcurrentProduct() 91 { 92 Parallel.For(0, 30000, (i) => 93 { 94 Product product = new Product(); 95 product.Name = "name" + i; 96 product.Category = "Category" + i; 97 product.SellPrice = i; 98 _currentQueue.Enqueue(product); 99 }); 100 Console.WriteLine("当前线程ID为{0}", Thread.CurrentThread.ManagedThreadId); 101 } 102 } 103 class Product 104 { 105 public string Name { get; set; } 106 public string Category { get; set; } 107 public int SellPrice { get; set; } 108 } 109 }