日期:2014-05-18  浏览次数:20736 次

多线程的锁定
我做了一个小测试是关于多线程的,但是结果与我期望的不同。
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace ThreadTest
{
   
  public class LockCodeArea
  {
  private int count = 10;
  public void ReduceCount()
  {
  while (true)
  {
  lock (this) 
  {
  Console.WriteLine("Current Count:{0}", count);
  Console.WriteLine("Current thread HashCode is :{0}", Thread.CurrentThread.GetHashCode());
  Thread.Sleep(100);
  --count;
  if (count > 0)
  continue;
  else
  break;
  }
  }
  }
  }
  class Program
  {
  static void Main(string[] args)
  {
  LockCodeArea testClass = new LockCodeArea();
  Thread firsThread = new Thread(new ThreadStart(testClass.ReduceCount));
  Thread secondThread = new Thread(new ThreadStart(testClass.ReduceCount));
  Console.WriteLine("Main HashCode is :{0}", Thread.CurrentThread.GetHashCode());
  Console.WriteLine("First thread Hashcode is :{0}",firsThread.GetHashCode());
  Console.WriteLine("Second thread HashCode is :{0}", secondThread.GetHashCode());
  firsThread.Start();
  secondThread.Start();
  if (!firsThread.IsAlive)
  Thread.Sleep(1000);
  Console.WriteLine("Press Any Key to Continue!");
  Console.WriteLine("Main HashCode is :{0}", Thread.CurrentThread.GetHashCode());
  Console.ReadLine();

  }
  }
}
本来是希望使用Lock之后,只存在要么firstThread减数,要么secondThread减数,为什么会有firstThread和secondThead
交替减数的情况。我已经使用Lock锁定代码区了。???各位帮帮忙呀。

------解决方案--------------------
注意,lock锁定的块同一时间只有一个线程能访问,你目前的代码锁定的是while内的代码。也就是说有2个线程都到达了循环内,一个现成continue的时候另一个线程乘机执行Console.WriteLine....
如果要同一时间只有1个线程能执行整个循环,就要把整个循环(10次)都锁住,也就是说:
C# code

 public void ReduceCount()
        {
            lock (this)
            {
                while (true)
                {
                    Console.WriteLine("Current Count:{0}", count);
                    Console.WriteLine("Current thread HashCode is :{0}", Thread.CurrentThread.GetHashCode());
                    Thread.Sleep(100);
                    --count;
                    if (count > 0)
                        continue;
                    else
                        break;
                }
            }
        }