日期:2014-05-17  浏览次数:20387 次

多线程 锁的问题????????????????????????????
原贴地址http://topic.csdn.net/u/20111007/11/a684438d-123c-4687-af7c-5e8db4b316c6.html?49311


求达人解!

------解决方案--------------------
C# code

void funcB(int i)
  {
  if (!list.Contains(i))
  {
     lock (dummyObject)
     {
    [color=#FF0000] if (!list.Contains(i))[/color]
       {
         list.Add(i);
         System.Diagnostics.Debug.WriteLine(i);
        }
     }
  }
  else
  {
  System.Diagnostics.Debug.WriteLine(i.ToString() + " existed");
  }
  }

------解决方案--------------------
God..

失误,

在lock 里 还判断一次,

if (!list.Contains(i))
{
}
------解决方案--------------------
dummyobject 

你锁这个变量,和你的list 集合是什么关系。同一个类下面?

是否是 private static object dummyobject=new object();

list 又是什么访问级别。
------解决方案--------------------
C# code

Thread t1 = new Thread(new ThreadStart(FunA));
            t1.Start();
            Thread t2 = new Thread(new ThreadStart(FunA));
            t2.Start();
            Thread t3 = new Thread(new ThreadStart(FunA));
            t3.Start();
            Thread t4 = new Thread(new ThreadStart(FunA));
            t4.Start();

            Thread.Sleep(3000);
            Console.WriteLine("the length of lists is {0}", lists.Count);
            Console.WriteLine("the elements of lists are:");
            foreach (int i in lists)
            {
                Console.Write(i.ToString() + " ");
            }
            Console.ReadLine();

public static void FunA()
        {
            Random rand = new Random();
            FunB(rand.Next(1, 10));
        }
        public static void FunB(Int32 i)
        {
            Console.WriteLine(i);
            if (!lists.Contains(i))
            {
                lock (lockObject)
                {
                    if (!lists.Contains(i))
                    {
                        lists.Add(i);
                    }
                }
            }
        }