-
Notifications
You must be signed in to change notification settings - Fork 0
/
SharedBuffer.java
81 lines (69 loc) · 1.27 KB
/
SharedBuffer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
public class SharedBuffer<WorkItem>
{
private static int BUFFER_SIZE;
public int count, in, out;
int EmptyCount, FullCount;
private WorkItem[] buffer;
boolean Open;
public SharedBuffer(int BUFFER_SIZE)
{
this.BUFFER_SIZE = BUFFER_SIZE;
count = 0;
in = 0;
out = 0;
FullCount = 0;
EmptyCount = 0;
Open = true;
buffer = (WorkItem[]) new Object[BUFFER_SIZE];
}
public synchronized void close()
{
Open = false;
}
public synchronized void put (WorkItem item, String Name)
{
while(count == BUFFER_SIZE)
{
try
{
System.out.println("The queue is full. " + Name + " is waiting.");
FullCount++;
wait();
}
catch (InterruptedException ie) {}
}
if(count == 0)
{
}
buffer[in] = item;
in = (in + 1) % BUFFER_SIZE;
count++;
notify();
}
public synchronized WorkItem get(String Name)
{
WorkItem item;
while (count == 0)
{
if(!Open)
{
break;
}
System.out.println("The queue is empty. " + Name + " is waiting.");
EmptyCount++;
try
{
wait(100);
}
catch (InterruptedException ie)
{
break;
}
}
item = buffer[out];
out = (out+1) % BUFFER_SIZE;
count--;
notify();
return item;
}
}