消费者与生产者

来源:互联网 发布:js获取 鼠标位置 编辑:程序博客网 时间:2024/06/05 18:07
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;


namespace ProductCreate
{
    class Program
    {
        static void Main(string[] args)
        {
            //定义了一个对象池:最大个数是100个。
            Product[] ProductPool =new Product[100];
            int index = 0;//以上来消费到0。现在没有产品


            object objLock = new object();


            //初始化10个消费者
            for (int i = 0; i < 10; i++)
            {
                Thread thread =new Thread(() =>
                    {
                        while (true)//不停的消费
                        {
                            //只要锁同一个对象那么就会互斥。
                            lock (objLock)//锁住对象:objLock。同一时间只能有一个线程获得此对象的锁。
                            {
                                if (index > 0)
                                {
                                    ProductPool[index - 1] = null;
                                    index--;
                                    Console.WriteLine("消费一个产品");
                                    
                                } 
                            }//lock的花括号执行完成。对象锁被释放。
                            Thread.Sleep(30);
                        }
                    });
                thread.IsBackground = true;
                thread.Start();
            }




            //初始化3个生成者


            //初始化10个消费者
            for (int i = 0; i < 3; i++)
            {
                Thread thread = new Thread(() =>
                {
                    while (true)//不停的消费
                    {
                        lock (objLock)
                        {
                            if (index < 100)
                            {
                                ProductPool[index] = new Product() { Id = 0, ProName = DateTime.Now.ToString() };
                                index++;
                                Console.WriteLine("生成一个产品");
                            } 
                        }


                        Thread.Sleep(30);
                    }
                });
                thread.IsBackground = true;
                thread.Start();
            }


            Console.ReadKey();


        }
    }


    public class  Product
    {
        public int Id { get; set; }


        public string ProName { get; set; }
    }
}