学习线程同步,很经典的一个例子。 
 
[C#] 纯文本查看 复制代码 class Program
    {
        static void Main(string[] args)
        {
            //定义产品池
            product[] productpool = new product[100];
            //定义产品索引
            int index = 0;
            //定义锁定对象
            object lockobj = new object();
              
            #region 生产与消费
  
            //定义5个生产者
            for (int i = 0; i < 5; i++)
            {
                new Thread(() =>
                {
                    while (true)
                    {
                        //执行到这里的时候,当前线程停下来等待拿到lockobj对象上面对应的锁
                        lock (lockobj)//lock一个引用类型对象
                        {
                            if (index < 100)
                            {
                                product p = new product();
                                productpool[index] = p;
                                Console.WriteLine("生产一个产品:" + Thread.CurrentThread.ManagedThreadId);
                                index++;
                            }
                        }
                        Thread.Sleep(100);
                    }
                }).Start();
            }
  
            //定义10个消费者
            for (int i = 0; i < 10; i++)
            {
                new Thread(() =>
                {
                    while (true)
                    {
                        lock (lockobj)
                        {
                            if (index > 0)
                            {
                                productpool[index - 1] = null;//消费一个产品
                                Console.WriteLine("消费一个产品:" + Thread.CurrentThread.ManagedThreadId);
                                index--;
                            }
                        }
                        Thread.Sleep(500);
                    }
                }).Start();
            }
            #endregion
  
            Console.ReadKey();
        }
    }
    class product
    {
        /// <summary>
        /// 产品名称
        /// </summary>
        string productName { get; set; }
    } 
 |