标签:
1.新建项目(控制台应用程序)
2.新建一个类:OrderIdHelper.cs
1 /// <summary> 2 /// 订单助手 3 /// </summary> 4 class OrderIdHelper 5 { 6 private static readonly object Locker = new object(); 7 private static string _tempId = ""; 8 9 /// <summary> 10 /// 生成订单编号 11 /// </summary> 12 public static void GenerateId() 13 { 14 lock (Locker) //lock 关键字可确保当一个线程位于代码的临界区时,另一个线程不会进入该临界区。 15 { 16 var orderId = "Wen" + DateTime.Now.ToString("yyyyMMddHHmmss"); //年月日时分秒 17 18 if (string.Equals(_tempId, orderId)) 19 { 20 throw new Exception("订单号重复!"); 21 } 22 23 _tempId = orderId; 24 25 Console.WriteLine(orderId); 26 } 27 } 28 }
3.Program.cs
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 //创建包含两个线程的数组 6 var threads = new Thread[2] 7 { 8 new Thread(OrderIdHelper.GenerateId), 9 new Thread(OrderIdHelper.GenerateId), 10 }; 11 12 foreach (var thread in threads) 13 { 14 //线程启动 15 thread.Start(); 16 } 17 18 Console.Read(); 19 } 20 }
4.结果:=====OrderIdDemo_1.rar 点我下载=====
5.======================未完,待续=======================
标签:
原文地址:http://www.cnblogs.com/liqingwen/p/4573833.html