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

C#的多线程锁定问题
大家好,我在学习C#多线程编程时遇到了下面的问题。
我建立了三个线程,一个生产者Producer和两个消费者Consumer,在HoldIntegerSync的内部对多线程读取与写入进行同步,但是为什么我在HoldIntegerSync的get和set中的lock锁定不起作用呢?所有线程都能同时进入被lock包裹的代码。
C# code
 
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace ConsoleApplication2
{
    public class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Main Start.");

            try
            {
                HoldIntegerSync his = new HoldIntegerSync();
                Consumer consumer = new Consumer(his);
                Consumer consumerTwo = new Consumer(his);

                Producer producer = new Producer(his);

                Thread producerThread = new Thread(new ThreadStart(producer.Produce));
                producerThread.Name = "Producer";

                Thread consumerThread1 = new Thread(new ThreadStart(consumer.Consume));
                consumerThread1.Name = "Consumer";

                Thread consumerThread2 = new Thread(new ThreadStart(consumerTwo.Consume));
                consumerThread2.Name = "ConsumerTwo";

                consumerThread1.Start();
                consumerThread2.Start();
                producerThread.Start();

            }
            catch (Exception e)
            {
                Console.WriteLine("Catch Exception : \n" + e.ToString());

                Console.WriteLine("Exception Message : \n" + e.Message);

                Console.WriteLine("Exception Inner :\n" + e.InnerException);
            }

            Console.WriteLine("Main End.");
        }
    }

    class Producer
    {
        private Random rd = new Random(10);
       
        private HoldIntegerSync sync;
        public Producer(HoldIntegerSync his)
        {
            this.sync = his;
        }

        public void Produce()
        {
            sync.Buffer = rd.Next();
        }
    }

    class Consumer
    {
        private HoldIntegerSync sync;
        public Consumer(HoldIntegerSync his)
        {
            this.