您的位置:首页 > 其它

多线程计数,怎么保持计数准确的方法

2014-01-10 15:35 459 查看
CommonSigleton MyCounter =CommonSigleton.Instance;  /// <summary>  /// 线程工作  /// </summary>public void DoSomeWork(){    ///构造显示字符串    string results = "";

    ///创建一个Sigleton实例

    System.Threading.Thread.Sleep(100);

    int i = 0;    while (MyCounter.GetCounter() < 200)    {        //保证计数与输出一致,即便计数与输出之间加上时间间隔也会为这块区域加锁,防止其他线程操作        lock (this)        {            ///开始计数            MyCounter.Add();            System.Threading.Thread.Sleep(100);            Thread thread = Thread.CurrentThread;            results += "线程";            results += i++.ToString() + "――〉" + thread.Name + " ";            results += "当前的计数:";            results += MyCounter.GetCounter().ToString();            results += "\n";

            Console.WriteLine(results);

            // 清空显示字符串            results = "";        }    }}

  public void StartMain()  {

   Thread thread0 = Thread.CurrentThread;    thread0.Name = "Thread 0";    Thread thread1 =new Thread(new ThreadStart(DoSomeWork));    thread1.Name = "Thread 1";    Thread thread2 =new Thread(new ThreadStart(DoSomeWork));    thread2.Name = "Thread 2";    Thread thread3 =new Thread(new ThreadStart(DoSomeWork));    thread3.Name = "Thread 3";

            thread1.Start();             thread2.Start();             thread3.Start();    ///线程0也只执行和其他线程相同的工作   DoSomeWork();   } }

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  多线程计数