c# 简单队列的实现

我们知道队列  就是在内容内存分配连续的内存空间,实现先进先出的逻辑,FIFO(LILO),

 这里用到了.net 4.0 的ConcurrentQueue类,(带线程安全的队列类),也可以用Queue ,多线程中自行同步。

代码可直接复制运行

 1 using System;

 2 using System.Collections.Concurrent;

 3 using System.Collections.Generic;

 4 using System.Text;

 5 using System.Threading;

 6 

 7 namespace SingleLinkedList

 8 {

 9     class Program

10     {

11         static void Main(string[] args)

12         {

13             List<student> stu = new List<student>(new student[] { new student("张三", "", 20), new student("李四", "", 22), new student("王五", "", 24), new student("赵六", "", 18), new student("陈七", "", 25)});

14             studentManager<student> stuMag = new studentManager<student>();

15             foreach (var item in stu)

16             {

17                 stuMag.Insertstudent(item);

18             }

19             while (stuMag.Getcount() > 0)

20             {

21                 student output = stuMag.GetAndRemove();

22                 Console.WriteLine(string.Format("姓名:{0} | 性别:{1} | 年龄:{2}", output.name, output.sex, output.age));

23                 Thread.Sleep(2000);

24             }

25             Console.ReadLine();

26         }        

27     }

28     //定义一个学生类;

29     public class student

30     {

31         public string name { get; set; }

32         public string sex { get; set; }

33         public int age { get; set; }

34         public student()

35         {

36             name = null; sex = null; age = 0;

37         }

38         public student(string Name, string Sex, int Age)

39         {

40             name = Name; sex = Sex; age = Age;

41         }

42     }

43     //定义一个带类型参数的队列管理类;

44     public class studentManager<T> where T:new ()

45     {

46         ConcurrentQueue<T> stuQueue =null; //用到了.net 4.0的ConcurrentQuene 带线程安全的队列类【FIFO】

47         public studentManager()

48         {

49             stuQueue = new ConcurrentQueue<T>();

50         }

51         //获取队头操作

52         public T Getstudent()

53         {

54             T t = new T();

55 

56             if (!stuQueue.IsEmpty)

57             {

58                 stuQueue.TryPeek(out t);

59                 return t;

60             }

61             else

62             {

63                 return default(T);

64             }

65         }

66         //入队操作

67         public void Insertstudent(T t)

68         {

69             stuQueue.Enqueue(t);

70         }

71         //获取并移除队头(出队)

72         public T GetAndRemove()

73         {

74             T t = new T();

75             stuQueue.TryDequeue(out t);

76             return t;

77         }

78         //获取队列数

79         public int Getcount()

80         {

81             return stuQueue.Count;

82         }

83     }

84 }

 运行结果如下:

c# 简单队列的实现

你可能感兴趣的:(C#)