/Users/lyon/j4p/src/thread/Queues.java
|
1 package thread;
2
3 public class Queues {
4 private static final int queue_size = 10;
5 private Object[] queue =
6 new Object[queue_size];
7
8 private int head = 0;
9 private int tail = 0;
10
11 synchronized public void
12 enqueue(Object item) {
13 ++head;
14 int i = head % queue_size;
15 queue[i] = item;
16 this.notify();
17 }
18
19 synchronized public Object dequeue() {
20 try {
21 while (head == tail) {
22 this.wait();
23 }
24 } catch (InterruptedException e) {
25 return null;
26 }
27 return queue[++tail % queue_size];
28 }
29
30 public static void main(String args[]) {
31 Queues q
32 = new Queues();
33 q.enqueue(q);
34 q.enqueue(q);
35 System.out.println(q);
36 System.out.println(q.dequeue());
37
38 }
39 }
40
41 class Consumer implements Runnable {
42 Queues q;
43
44 Consumer(Queues _q) {
45 q = _q;
46 }
47
48 public void run() {
49 while (true) {
50 System.out.println(
51 (String) q.dequeue());
52 }
53 }
54 }
55
56 class Producer {
57
58 public static void main(String args[]) {
59 Queues q =
60 new Queues();
61 Thread ct = new Thread(new Consumer(q));
62 Producer p = new Producer();
63 ct.start();
64 q.enqueue("This is my first entry");
65 q.enqueue("This is my second entry");
66 q.enqueue("This is my third entry");
67 q.enqueue("This is my third entry");
68 q.enqueue("This is my third entry");
69 q.enqueue("This is my third entry");
70 q.enqueue("This is my third entry");
71 q.enqueue("This is my third entry");
72 q.enqueue("This is my third entry");
73 q.enqueue("This is my third entry");
74 q.enqueue("This is my third entry");
75 }
76 }
77