多线程链式队列的控制台程序(转)

C#开发 2014-04-06 5760阅读 0评论 0收藏 收藏本文
本文转自:http://bbs.csdn.net/topics/210023993 要求:一:2个线程往队列写数据,1个线程从队列里面读数据 读取的是最后一个线程写的数据;(在控制台输出读和写的数据) 二:能区分是哪个线程写的数据 三:用exit命令结束线程 实现方法:
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {

        //堆栈是后进先出的
        static System.Collections.Stack stack = new System.Collections.Stack();
        //信号量控制线程
        static System.Threading.ManualResetEvent obj = new System.Threading.ManualResetEvent(false);

        //写入的对象
        public class Data
        {
            public Guid ID = Guid.NewGuid();
            public string ThreadName = System.Threading.Thread.CurrentThread.Name;

            public override string ToString()
            {
                return string.Format("{0}生成的{1}", ThreadName, ID);
            }

        }

        static void Main(string[] args)
        {
            obj.Reset();
            System.Threading.Thread t1 = new System.Threading.Thread(new System.Threading.ThreadStart(wirteData));
            System.Threading.Thread t2 = new System.Threading.Thread(new System.Threading.ThreadStart(wirteData));
            System.Threading.Thread t3 = new System.Threading.Thread(new System.Threading.ThreadStart(readData));
            t1.Name = "w1";
            t2.Name = "w2";
            t3.Name = "r1";

            t1.Start();
            t2.Start();
            t3.Start();

            //等待输入
            if (Console.ReadLine().ToLower() == "exit")
            {
                obj.Set();
                Console.WriteLine("退出!");
            }
        }
        //
        static Random rand = new Random(100);
        private static void wirteData()
        {
            //线程等待时间
            int i = rand.Next(3000, 4000);
            while (obj.WaitOne(i, false) == false)
            {
                Data data = new Data();
                lock (stack)
                {
                    stack.Push(data);
                }
                Console.WriteLine("写入:"+data.ToString());                
            }
            Console.WriteLine("退出!");
        }

        private static void readData()
        {
            int i = rand.Next(2000, 3000);
            while (obj.WaitOne(i, false) == false)
            {
                lock (stack)
                {
                    if (stack.Count > 0)
                    {
                        Data data = stack.Pop() as Data;
                        Console.WriteLine("读取:" + data.ToString());
                    }
                    else
                    {
                        Console.WriteLine("无数据!");
                    }

                }

            }
        }
    }
}
 

转载请注明:图享网 » 多线程链式队列的控制台程序(转)

文章评论

获取验证码