Queue學習

一,隊列的實現併發

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

namespace bingfa
{
    class Program
    {
        //實例引用類型的私有對象,用來實現鎖的操做,當這個對象釋放,下一個才能夠調用鎖住的方法
        private static object o = new object(); 

        static void Main(string[] args)
        {
            //開啓線程監聽
            UserHelper.Instance.Start();

            //實現多併發
            Task t1 = Task.Factory.StartNew(() =>
            {
                AddUser();
            });
            Task t2 = Task.Factory.StartNew(() =>
            {
                AddUser();
            });
            Task.WaitAll(t1, t2);

            Console.ReadKey();
        }

        //集合數據添加操做
        static void AddUser()
        {
            Parallel.For(0, 10, (i) =>
            {
                lock (o)   // 添加鎖,避免丟失
                {
                    UserHelper.Instance.AddQueue("Name" + i);
                }
            });
        }
    }

    //隊列臨時類  
    public class UserInfo
    {
        public string Name { get; set; }
    }

    public class UserHelper
    {
        #region 使用隊列和鎖,實現當多併發是出現的請求丟失

        public readonly static UserHelper Instance = new UserHelper();
        private UserHelper()
        { }

        private Queue<UserInfo> LQueue = new Queue<UserInfo>();

        public void AddQueue(string Name) //入列  
        {
            UserInfo qinfo = new UserInfo();
            qinfo.Name = Name;
            LQueue.Enqueue(qinfo); 
        }

        public void Start()//啓動線程  
        {
            Thread thread = new Thread(threadStart);
            thread.IsBackground = true;
            thread.Start();
        }

        private void threadStart() //現成監聽方法
        {
            while (true)
            {
                if (LQueue.Count > 0)
                {
                    try
                    {
                        ShowQueue();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }
                else
                {
                    //沒有任務,休息3秒鐘  
                    Thread.Sleep(3000);
                }
            }
        }

        //執行的方法,便是當有對象進入隊列的實現方法
        private void ShowQueue()   
        {
            while (LQueue.Count > 0)
            {
                try
                {
                    //從隊列中取出數據進行操做 
                    UserInfo qinfo = LQueue.Dequeue();
                    Console.WriteLine(qinfo.Name);

                }
                catch (Exception ex)
                {
                    throw;
                }
            }
        }

        #endregion
    }
}
相關文章
相關標籤/搜索