c# 多线程 生产者/消费者队列 源码

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

namespace ConsoleApplication1
{
      class Product:IDisposable
    {
        EventWaitHandle EV = new AutoResetEvent(false);
        object ob = new object();
        Queue<string> ppe=new Queue<string>();
        Thread t;
        public Product()
        {
            t = new Thread(new ThreadStart(work));
            t.Start();
        }

        public void SetIn(string ls)
        {
            ppe.Enqueue(ls);
            EV.Set();
        }

        public void Dispose()
        {
            SetIn(null);
            t.Join();
            EV.Close();
        }

        public void work()
        {
            while (true)
            {
                string talk = null;
                lock (ob)
                    if (ppe.Count > 0)
                    {
                        talk = ppe.Dequeue();
                        if (talk == null)
                            return;
                    }
                    
                if (talk != null)
                {
                    Console.WriteLine(talk);
                    Thread.Sleep(1000);
                }
                else
                {
                    EV.WaitOne();
                }
            }
        }
    }

    class rheMain
    {
        static void Main()
        {
            using (Product pt = new Product())
            {
                pt.SetIn("hello!");
                for (int i = 1; i <= 5; i++)
                {
                    pt.SetIn("say:" + i);
                }
                pt.SetIn("good by!");
                 
            }

            //Product pt = new Product();

            //pt.SetIn("hello!");
            //for (int i = 1; i <= 5; i++)
            //{
            //    pt.SetIn("say:" + i);
            //}
            //pt.SetIn("good by!");
            //pt.Dispose();

            Console.WriteLine("oVER!");
            //Console.ReadLine();
        }
    }
}


你可能感兴趣的:(thread,多线程,object,String,C#,null)