Repository navigation
Expand file tree
/
Copy pathProducerConsumer.java
More file actions
92 lines (77 loc) · 1.74 KB
/
Copy pathProducerConsumer.java
File metadata and controls
92 lines (77 loc) · 1.74 KB
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
82
83
84
85
86
87
88
89
90
91
92
import java.util.Random;
// A correct implementation of a producer and consumer.
public class ProducerConsumer {
public static void main(String args[]) {
Queue q = new Queue();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}
class Queue {
int buffer;
boolean bufferUpdated = false;
synchronized int get() {
if(!bufferUpdated)
try {
System.out.println("Ops! Not ready yet, in production... Keep waiting");
wait();
}catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + buffer);
bufferUpdated = false;
notify();
return buffer;
}
synchronized void put(int n) {
if(bufferUpdated)
try {
System.out.println("Ops! Not ready yet, consuming... Keep waiting");
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.buffer = n;
bufferUpdated = true;
System.out.println("Put: " + n);
notify();
}
}
class Producer implements Runnable {
Queue q;
Random randGen = new Random();
Producer(Queue q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
try{//simulate production time
Thread.sleep(500*(randGen.nextInt(3)+1));
}catch(Exception e){
e.printStackTrace();
}
q.put(i++);
}
}
}
class Consumer implements Runnable {
Queue q;
Random randGen = new Random();
Consumer(Queue q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
try{//simulate production time
Thread.sleep(500*(randGen.nextInt(3)+1));
}catch(Exception e){
e.printStackTrace();
}
q.get();
}
}
}