生产者消费者

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;


namespace ProduceConsume
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建大小为100的数据库连接对象池
            MySqlConnection[] connArr = new MySqlConnection[100];

            // 数组索引
            int index = -1;

            // 创建10个消费者
            for (int i = 0; i < 10; i++)
            {
                // 其中的一个消费者
                Thread thread = new Thread(() => {
                    while (true)
                    {
                        lock (connArr)
                        {
                            if (index >= 0)
                            {
                                Console.WriteLine("{0},正在消费第{0}个连接对象...", 
                                    Thread.CurrentThread.Name,  index);
                                connArr[index] = null;
                                index--;
                            }
                            else
                            {
                                Console.WriteLine("连接对象使用完毕!");
                            } 
                        }
                        Thread.Sleep(200);
                    }

                });
                
                thread.Name = "我是消费线程" + i;
                thread.IsBackground = true;
                thread.Start();
            }

            // 创建5个生产者
            for (int i = 0; i < 5; i++)
            {
                // 其中的一个生产者
                Thread thread = new Thread(() => {
                    while (true)
                    {
                        lock (connArr)
                        {
                            if (index < 100)
                            {
                                Console.WriteLine("{0},正在生产第{1}个连接对象...",
                                    Thread.CurrentThread.Name, index + 1);
                                connArr[index + 1] = new MySqlConnection();
                                index++;
                            }
                            else
                            {
                                Console.WriteLine("已生产了{0}个连接对象!", index);
                            } 
                        }
                        Thread.Sleep(100);
                    }

                });
                thread.Name = "我是生产线程" + i;
                thread.IsBackground = true;
                thread.Start();
            }

            Console.ReadKey();
        }
        
    }

    class MySqlConnection
    {
        public int Id { get; set; }
        public string CommandText { get; set; }

        public void Open() { }
    }
}
View Code

posted @ 2014-12-12 22:07  萌浩  阅读(125)  评论(0编辑  收藏  举报