C# 线程顺序执行。

今天看了Jetlian的博客,自己也实现了一下,大体一样,部分修改了一下。有错误之处望不吝赐教,感激不尽!

http://www.cnblogs.com/jetlian/archive/2015/03/01/4307584.html

 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             ThreadQueue pool = new ThreadQueue(new string[] { "A", "B", "C", "C", "C" }, 1);
 6             Console.ReadKey();
 7         }
 8     }
 9 
10     class ThreadQueue
11     {
12         private static object _lockObj = new object();//锁对象
13         private static string[] _reportList;//打印的集合
14         private static int _curIndex = -1;//当前下标
15         private static int _reportCount;//打印次数
16         private static int _curNumber;// 当前次数
17         public ThreadQueue(string[] reportList, int count)
18         {
19             if (reportList == null || reportList.Length < 1 || count < 1)
20             {
21                 return;
22             }
23             _reportCount = count;
24             _reportList = reportList;
25             for (int i = 0; i < reportList.Length; i++)
26             {
27                 new Thread(PrintNumber) { Name = "Thread " + i }.Start(new KeyValuePair<int, string>(i, reportList[i]));
28             }
29         }
30 
31         /// <summary>
32         /// 实现排队打印
33         /// </summary>
34         /// <param name="objData"></param>
35         private void PrintNumber(object objData)
36         {
37             while (_curNumber < _reportCount)
38             {
39                 KeyValuePair<int, string> data = (KeyValuePair<int, string>)objData;
40                 lock (_lockObj)
41                 {
42                     if (data.Key == _curIndex + 1 || (_curIndex == _reportList.Length - 1 && data.Key == 0))
43                     {
44                         Console.WriteLine("{0}:{1}", Thread.CurrentThread.Name, data.Value);
45                         _curIndex = data.Key;
46                         if (_curIndex == _reportList.Length - 1)
47                         {
48                             _curNumber++;
49                         }
50                         Monitor.PulseAll(_lockObj);
51                     }
52                     else
53                     {
54                         Monitor.Wait(_lockObj);
55                     }
56                 }
57             }
58         }
59     }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。