1 using System;
2 using System.Collections;
3 using System.Collections.Generic;
4 using System.Threading;
5
6 public class Queue<v> : iQueue<v>
{
7
8 public List<v>
list;
9 int cursor, current, max, flag;
10 const int reduce =
5;
11
12 public Queue() {
13 list =
new List<v>
();
14 cursor = -
1;
15 current =
0;
16 max =
0;
17 flag = -
1;
18 }
19
20 private object locker =
new object();
21 public bool Dequeue(
ref v data) {
22 lock (locker)
23 if (max >
0) {
24 if ((current +
1) - (cursor +
1) == max +
1 || max - current >
0)
25 cursor++
;
26 else
27 cursor =
0;
28
29 data =
list[cursor];
30 max--
;
31 return true;
32 }
else
33 return false;
34 }
35
36 private int count =
0;
37 public void Enqueue(v data) {
38 lock (locker) {
39
40 if (current ==
list.Count)
41 list.Add(data);
42 else
43 list[current] =
data;
44
45 if (cursor > -
1 && current - cursor - max ==
1) {
46 flag =
current;
47 current =
0;
48 }
else {
49 current++
;
50 while (cursor < current && current <=
flag)
51 current++
;
52 }
53
54 max++
;
55
56 if (max + Math.Max(current, cursor) <
list.Count) {
57 if (++count ==
reduce) {
58 list.RemoveAt(list.Count -
1);
59 list.TrimExcess();
60 count -=
reduce;
61 }
62 }
else
63 count =
0;
64 }
65 }
66
67 public bool Peek(
ref v data) {
68 lock (locker)
69 if (max >
0) {
70 int index =
cursor;
71 if ((current +
1) - (cursor +
1) == max +
1 || max - current >
0)
72 index++
;
73 else
74 index =
0;
75
76 data =
list[index];
77 return true;
78 }
else
79 return false;
80 }
81 }
82
83 public interface iQueue<v>
{
84 void Enqueue(v data);
85 bool Dequeue(
ref v data);
86 bool Peek(
ref v data);
87 }
转载于:https://www.cnblogs.com/c233/p/10979324.html