zoukankan      html  css  js  c++  java
  • 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     }
  • 相关阅读:
    ant中build.xml文件解释
    mysql练习题
    Mysql基本知识
    Python Socket 简单聊天室2
    Python Socket 简单聊天室1
    Python 导入模块
    Python 文件的处理
    Python yield
    Python 内置函数
    Python 生成验证码
  • 原文地址:https://www.cnblogs.com/CanFly/p/4308350.html
Copyright © 2011-2022 走看看