首页 / C#开发 / 正文

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

8265 发布于: 2014-04-06 读完约需8分钟
本文转自: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("无数据!");
                    }

                }

            }
        }
    }
}
 

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: C# DataTable转换成List的方法与测试

下一篇: 可返回记录总数的SQL2005,SQL2012通用分页方法

本文永久链接码友网 » 多线程链式队列的控制台程序(转)

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册