public class ThreadInteroperateWithLock
{
    private int m_count;
    private object m_synLock;
    public ThreadInteroperateWithLock() 
    {
        m_count = 0;
        m_synLock = new object();
    }    public int Count { get { return m_count; } }    public void Add() 
    {
        lock (this)
        {
            m_count++;
        }
    }
}ThreadInteroperateWithLock ope = new ThreadInteroperateWithLock();
Thread[] threadArray = new Thread[100];
for (int i = 0; i < 100; i++)
{
    Thread thread = new Thread(new ThreadStart(ope.Add));
    thread.IsBackground = false;
    threadArray[i] = thread;
}
for (int i = 0; i < 100; i++)
{
    threadArray[i].Start();
}
Console.WriteLine(ope.Count);
Console.ReadKey();输出还是不稳定,是不是我的代码没有对?

解决方案 »

  1.   

      private static readonly object m_synLock; 这样就可以了
      

  2.   

    可能是你计算机比较高级的原因,可以加个Thread.Sleep(10),让线程冲突的可能性提高一些估计就出问题了。
      

  3.   

    lock (this)这里出问题了,你应该用你定义的object啊 lock (m_synLock)
      

  4.   

    如果再不行,就用嵌套子类来做双向控制。
            private  static ThreadInteroperateWithLock clone = null;
    ............
    if (clone == null)
                   {
                       lock (m_synLock)
                        {
                             clone=Nested.Clone;
                           m_count++;
                }
                     
                   } class Nested///嵌套类延时实例化。
           {
               static Nested()
               {
               }
               internal static readonly ThreadInteroperateWithLockClone = new ThreadInteroperateWithLock();
           }
      

  5.   

    一样的啊,我只构造了一个实例,this和m_synLock没啥区别啊。
    而且你可以试试把m_synLock替换上去,貌似还是有问题。
      

  6.   

    public void Add() 
        {
            lock (m_synLock)
            {
                m_count++;
            }
        }
      

  7.   

    lock是检测括号里面的对象是不是被其他lock占用了。
    你的lock里面用的this。这里是一个对象。如果这个类再次被实例化,那么检测不到之前实例化的对象被Lock了。
    所以不起作用。简单的办法就是lock一个静态对象。
      

  8.   

    答案找到了,说来还是非常愚蠢的一个错误:
    The problem here would be that you're kicking off the threads and they're not entirely finished by the time of your call to write output to the console.The loop starts off i threads, we'll imagine these as bees going of collecting as work, not all going to the same food source so some take longer to return than others; then, back at the hive, we suddenly say: "Hey, bees, I need a headcount!", "...1, 2, 3..., only three?" No, some i-3 are still scrounging around outside!So, the idea is that we must have an indicator of when work is completed, or a homing signal of sorts to get all bees back to the hive for the headcount. This can be done with Join, or manual state checking (which essentially has you holding out until the last sojourner returns.)